【发布时间】:2016-11-08 04:36:23
【问题描述】:
Custom_View.xaml
<UserControl>
<local:Custom_Text_Field
Custom_Text_Field_Color="{x:Bind ViewModel.Color1 , Mode=TwoWay}">
</local:Custom_Text_Field>
<local:Custom_Text_Field
Custom_Text_Field_Color="{x:Bind ViewModel.Color2 , Mode=TwoWay}">
</local:Custom_Text_Field>
<Button Click="{x:Bind ViewModel.ChangeColor"/>
</UserControl>
Custom_View.cs
public sealed partial class Custom_View : UserControl
{
public Custom_View_VM ViewModel { get; set; }
public Custom_View()
{
ViewModel = new Custom_View_VM();
this.InitializeComponent();
}
}
Custom_View_VM.cs
public class Custom_View_VM : NotificationBase
{
public Brush Color1 { get; set; }
public Brush Color2 { get; set; }
public void ChangeColor{//change color1 or color2};
}
我使用了这个例子中的 NotificationBase 类:https://blogs.msdn.microsoft.com/johnshews_blog/2015/09/09/a-minimal-mvvm-uwp-app/
如果我影响构造函数中 Color1 或 Color2 的值,它会起作用(更改视图),但在调用 ChangeColor 后,视图模型中的值会更改,但不会影响视图。
【问题讨论】:
-
通常你会在代码隐藏而不是 ViewModel 中创建 DependencyProperties。控件的使用者可以将控件的依赖属性绑定到它们的 ViewModel。
-
感谢您的回答,我在后面的 Custom_Text_Field 代码中创建了 DependencyProperties,我为我的 Custom_View 创建了一个 ViewModel,因为 UI 比我的示例更复杂,并且他与来自 Web 服务的数据链接: (
-
这里有 2 种不同类型的绑定:绑定到后面的代码(使用 Dependancy 属性)和绑定到 ViewModel(使用 INotifyPropertyChanged) - 不清楚哪一个不起作用:边框(使用DP)还是文本字段(绑定到 VM)?
-
Novitchi S 解决了我的问题,它是绑定到 VM =)
-
我已经删除了依赖属性部分来澄清
标签: c# xaml mvvm data-binding inotifypropertychanged