gpt4 book ai didi

WPF MVVM 绑定(bind)到 UserControl 的 DependencyProperty 不起作用

转载 作者:行者123 更新时间:2023-12-02 14:25:31 26 4
gpt4 key购买 nike

我试图坚持使用 MVVM 方法来构建我的 WPF 应用程序,但遇到了一个奇怪的绑定(bind)问题,感觉我错过了一些东西。

我有一个用户控件(PluginsTreeView),它有一个ViewModel(PluginsViewModel)驱动它。 PluginsTreeView 公开了字符串类型 (DocumentPath) 的公共(public) DependencyProperty。我的 MainWindow 在 XAML 中设置了此属性,但它似乎没有添加到我的 UserControl 中。我正在寻找一些关于为什么这不起作用的迹象。

PluginsTreeView.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);
}
}
....
}

MainWindow.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>

但是,当我从 MainWindow 的代码隐藏中设置 DependencyProperty 时,它似乎确实正确设置了该值。我试图找出这里的区别以及为什么代码隐藏方法有效而在 xaml 中设置属性却无效。

MainWindow.xaml.cs

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

MainWindowViewModel ViewModel = new MainWindowViewModel();
this.DataContext = ViewModel;

atv.DocumentPath = "from code behind"; //THIS WORKS!
}
....
}

通过 Snoop,我发现 XAML“来自 xaml”的值确实进入了属性,但我在 PluginsTreeView 中的 Set 方法仍然没有被命中。除非从 MainWindow 代码隐藏中设置值,否则我在那里作为调试工具的消息框不会弹出。

最佳答案

显然,您不应该向这些属性 setter 添加任何逻辑,因为仅当您从代码设置属性时才会调用它们。如果从 XAML 设置属性,则直接调用 SetValue() 方法。我最终注册了一个回调方法,现在一切正常:

public static readonly DependencyProperty DocumentPathProperty = DependencyProperty.Register("DocumentPath", typeof(string), typeof(PluginsTreeView), new FrameworkPropertyMetadata("initial value", OnValueChanged));

关于WPF MVVM 绑定(bind)到 UserControl 的 DependencyProperty 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12963200/

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