gen*_*nus 5 wpf xaml dependency-properties mvvm
我试图坚持使用 MVVM 方法来构建我的 WPF 应用程序,但遇到了一个奇怪的绑定问题,感觉我错过了一些东西。
我有一个用户控件 (PluginsTreeView),它有一个驱动它的 ViewModel (PluginsViewModel)。PluginsTreeView 公开了一个字符串类型 (DocumentPath) 的公共 DependencyProperty。我的 MainWindow 在 XAML 中设置了这个属性,但它似乎没有将它添加到我的 UserControl 中。我正在寻找一些关于为什么这不起作用的迹象。
插件TreeView.xaml.cs
public partial class PluginsTreeView: UserControl
{
public PluginsTreeView()
{
InitializeComponent();
ViewModel = new ViewModels.PluginsViewModel();
this.DataContext = ViewModel;
}
public static readonly DependencyProperty DocumentPathProperty =
DependencyProperty.Register("DocumentPath", typeof(string), typeof(PluginsTreeView), new FrameworkPropertyMetadata(""));
public string DocumentPath
{
get { return (string)GetValue(DocumentPathProperty); }
set
{
//*** This doesn't hit when value set from xaml, works fine when set from code behind
MessageBox.Show("DocumentPath");
SetValue(DocumentPathProperty, value);
ViewModel.SetDocumentPath(value);
}
}
....
}
Run Code Online (Sandbox Code Playgroud)
主窗口.xaml
我的 PluginsTreeView 永远不会得到值“测试路径”,我不知道为什么。我觉得我在这里错过了一些基本的东西。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Views="clr-namespace:Mediafour.Machine.EditorWPF.Views" x:Class="Mediafour.Machine.EditorWPF.MainWindow"
xmlns:uc="clr-namespace:Mediafour.Machine.EditorWPF.Views"
Title="MainWindow" Height="350" Width="600">
<Grid>
<uc:PluginsTreeView x:Name="atv" DocumentPath="from xaml" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
但是,当我从 MainWindow 的代码隐藏设置 DependencyProperty 时,它似乎确实正确设置了该值。我试图弄清楚这里的区别以及为什么代码隐藏方法有效而在 xaml 中设置属性无效。
主窗口.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MainWindowViewModel ViewModel = new MainWindowViewModel();
this.DataContext = ViewModel;
atv.DocumentPath = "from code behind"; //THIS WORKS!
}
....
}
Run Code Online (Sandbox Code Playgroud)
与 Snoop 混在一起,我看到来自 XAML“来自 xaml”的值确实进入了属性,但我在 PluginsTreeView 中的 Set 方法仍然没有被命中。除非从 MainWindow 代码隐藏设置值,否则我在那里作为调试工具的消息框不会弹出。
显然,您不应该向这些属性设置器添加任何逻辑,因为仅当您从代码设置属性时才会调用它们。如果从 XAML 设置属性,则直接调用 SetValue() 方法。我最终注册了一个回调方法,现在一切正常:
public static readonly DependencyProperty DocumentPathProperty = DependencyProperty.Register("DocumentPath", typeof(string), typeof(PluginsTreeView), new FrameworkPropertyMetadata("initial value", OnValueChanged));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3531 次 |
| 最近记录: |