You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绑定数据无法在UI更新:MVVM下Commander属性同步问题

问题:Commander类属性更新无法同步到UI(基于CommunityToolkit.MVVM)

我有一个名为Commander的类,它包含一个CurrentRound属性,该属性会每隔几秒在内部自动更新。我正在使用CommunityToolkit.MVVM框架,在ViewModel中声明了一个ObservableProperty类型的CurrentRound,并在ViewModel的构造函数中执行了currentRound = _commander.CurrentRound;赋值操作。

奇怪的是,当我在Commander类中设置断点暂停程序时,能在XAML视图文件中看到更新后的值,但实际UI界面上并未显示更新。

初始代码

Commander类代码

public partial class Commander
{
    private readonly Communication communication;
    public Commander(Communication communication) 
    {
        this.communication = communication;
        ThreadStart work = this.NameOfMethodToCall;
        Thread thread = new Thread(work);
        thread.Start();
    }
    private async void NameOfMethodToCall()
    {
        while(true)
        {
            await Task.Delay(10000);
            Console.WriteLine("hey I'm the second thread!");
            CurrentRound = GetCurrentRound();
        }
    }
    public int CurrentRound { get; private set; } = 1;
}

ViewModel代码

public partial class ParametersViewModel: ObservableObject
{
    public ParametersViewModel(Commander commander, ...)
    {
        _commander = commander;
        currentRound = _commander.CurrentRound;
        ...
    }
    private readonly Commander _commander;
    ...

    [ObservableProperty]
    int currentRound;
    ...
}

View代码

<Label
   Text="{Binding CurrentRound, StringFormat='Current Round = {0}'}"
   HorizontalOptions="Center"
   FontAttributes="Bold"
   FontSize="Body"/>
...

更新1:问题仍存在

修改ViewModel和View代码后,问题依旧:

修改后的ViewModel代码

public partial class ParametersViewModel: ObservableObject
{
   ...
   [ObservableProperty]
   Commander myCommander;
   ...
}

修改后的View代码

<Label
   Text="{Binding MyCommander.CurrentRound, ...

更新2:临时解决但存疑惑

让Commander类继承ObservableObject并将CurrentRound设为ObservableProperty后,问题得到解决。但根据MVVM设计模式,模型和业务逻辑层不应关注UI绑定,这样做是否违反规范?有没有更合适的解决方法?

修改后的Commander类代码

public partial class Commander: ObservableObject
{
    ...
    [ObservableProperty]
    int currentRound = 1;
    ...
}

内容的提问来源于stack exchange,提问作者Mahyar Shokraeian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:10:20