【发布时间】:2018-04-06 06:35:40
【问题描述】:
我有一个使用 MVVM 模式用 C# 和 WPF 编写的用户控件。
我想要做的就是在绑定的 ViewModel 中有一个属性暴露在控件之外。我希望能够绑定到它,并且我希望对属性的任何更改都能被绑定到公开值的控件之外的任何东西拾取。
这听起来很简单,但它让我拔掉了我的头发(而且剩下的不多了)。
我在用户控件中有一个依赖属性。 ViewModel 具有实现 INotifyPropertyChanged 接口的属性,并且正在正确调用 PropertyChanged 事件。
一些问题: 1)如何在不破坏 MVVM 分离的情况下获取对 ViewModel 属性的更改并将其绑定到 Dependency 属性?到目前为止,我设法做到这一点的唯一方法是在后面的 Controls 代码中分配 ViewModels PropertyChanged 事件,这绝对不是 MVVM。
2) 使用上面的软糖,我可以让 Dependency 属性启动它的 PropertyChangedCallback,但是在控件之外绑定到它的任何东西都不会接收到更改。
必须有一种简单的方法来完成所有这些工作。请注意,我没有在这里发布任何代码 - 我希望不要用我现有的代码影响答案。还有,反正你们都可能会笑吧……
罗伯
好的,澄清一下 - 代码示例:
usercontrol 后面的代码:
public static DependencyProperty NewRepositoryRunProperty = DependencyProperty.Register("NewRepositoryRun", typeof(int?), typeof(GroupTree),
new FrameworkPropertyMetadata( null, new PropertyChangedCallback(OnNewRepositoryRunChanged)));
public int? NewRepositoryRun
{
get { return (int?)GetValue(NewRepositoryRunProperty); }
set
{
SetValue(NewRepositoryRunProperty, value);
}
}
private static void OnNewRepositoryRunChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != e.NewValue)
{
}
}
public GroupTree()
{
InitializeComponent();
GroupTreeVM vm = new GroupTreeVM();
this.DataContext = vm;
}
视图模型(GroupTreeVM.cs)
private int? _NewRepositoryRun;
public int? NewRepositoryRun
{
get
{
return _NewRepositoryRun;
}
set
{
_NewRepositoryRun = value;
NotifyPropertyChanged();
}
}
【问题讨论】:
-
请发布您的(相关)代码。
-
脱发问题可能属于其他网站 - 我们有 Beauty.SE 吗?也许您的 CRT 显示器正在杀死您。请改用纸质。或者从您的帖子中编辑掉与编程无关的文本...
-
我不知道你在说什么。 WPF 不支持或不支持头发,我在您的帖子中看不到任何 XAML 或 C# 代码。近距离投票。 -1
-
@Corcus 哦,ffs,那个。这里有一个提示:
(this.Content as FrameworkElement).DataContext = this是你能做的最愚蠢的事情。只需使用Binding.ElementName来引用根上定义的属性。 -
好吧,继续用锤子敲自己的头。毕竟是你的头。此外,POOF,不再有钢笔。喜欢坐下来小便。
标签: c# wpf mvvm user-controls