gpt4 book ai didi

c# - 如何在 WPF 中强制重新绑定(bind) WinRT?

转载 作者:行者123 更新时间:2023-12-03 10:35:26 24 4
gpt4 key购买 nike

我有一个基于 prism 的 WinRT 项目,其中包含多个页面、用户控件等。
出于某种原因,我需要将多个 View 绑定(bind)到 View 模型访问的单个模型对象(每个模型对象都属于一个 View )。
单个模型对象像其他对象一样由 Unity 容器注入(inject),例如需要像 eventtaggregator 一样单例。
为了简单起见,我做了一个例子,每个 View 中只有一个 bool 变量绑定(bind)到一个复选框,它应该在 View 上同步。
我的问题是:当我选中主页中的框时,第二页中的复选框在导航到该页面时遵循该值(示例中为 UserInpuPage),但不是主页上 UserControl 位置中的复选框。
在调试 session 之后,我看到单个模型中的变量具有正确的值,但用户控件(示例中的 MyUserControl)上的 GUI 没有更新。
WinRT 库中似乎不存在像 WPF 中的 GetBindingExpression(...) 和 UpdateTarget() 这样的机制。
出于设计原因(使用 prism mvvm,我不想打破 vm 的 Autowiring 和动态实例化的概念)在页面的资源部分和/或用户控件中定义的静态上下文不是我想要的。

如何使用模型实现用户控件中复选框的更新,其方式与导航后对 userinputpage 的工作方式相同?
任何帮助,将不胜感激。

// Interface mendatory to work with Unitiy-Injection for RegisterInstance<ISingletonVM>(...)
public interface ISingletonVM
{
bool TestChecked{ get; set; }
}

public class SingletonVM : BindableBase, ISingletonVM
{

bool _testChecked = false;
public bool TestChecked
{
get
{
return _testChecked;
}

set
{
SetProperty(ref _testChecked, value);
}
}
}

这是 View 模型中的相关代码(对于每个 vm 都相同,但在这种情况下来自 usercontrol 的 vm):
class MyUserControlViewModel : ViewModel
{
private readonly ISingletonVM _singletonVM;

public MyUserControlViewModel(ISingletonVM singletonVM)
{
_singletonVM = singletonVM;
}

public bool TestChecked
{
get
{
return _singletonVM.TestChecked;
}

set
{
_singletonVM.TestChecked = value;
}
}
}

三个 View 的相关 XAML 代码片段:

主页:
<prism:VisualStateAwarePage x:Name="pageRoot"  x:Class="HelloWorldWithContainer.Views.MainPage"...>
...
<StackPanel Grid.Row="2" Orientation="Horizontal">
<ctrl:MyUserControl ></ctrl:MyUserControl>
<CheckBox IsChecked="{Binding TestChecked, Mode=TwoWay}" Content="CheckBox" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
...

用户输入页:
<prism:VisualStateAwarePage x:Name="pageRoot"
x:Class="HelloWorldWithContainer.Views.UserInputPage"
...
<CheckBox IsChecked="{Binding TestChecked, Mode=TwoWay}" Content="CheckBox" HorizontalAlignment="Left" Margin="440,190,0,0" VerticalAlignment="Top"/>
...

用户控制:
<UserControl
x:Class="HelloWorldWithContainer.Views.MyUserControl" prism:ViewModelLocator.AutoWireViewModel="True"
<Grid>
<CheckBox Content="CheckBox" IsChecked="{Binding TestChecked, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="282"/>
</Grid>

最佳答案

您的用户控件永远不会收到有关 MyUserControlViewModel.TestChecked 更改的通知属性,这就是为什么 View 永远不会更新的原因。您可以做的一件事是订阅您的 SingletonVM.PropertyChanged MyUserControlViewModel 的构造函数中的事件.您的 ISingletonVM需要执行INotifyPropertyChanged界面。所以MyUserControlViewModel的构造函数将是这样的:

public MyUserControlViewModel(ISingletonVM singletonVM)
{
_singletonVM = singletonVM;
_singletonVM.PropertyChanged += (sender, args) => OnPropertyChanged("TestChecked");
}

关于c# - 如何在 WPF 中强制重新绑定(bind) WinRT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com