我想貼近MVVM的方法來建立我的WPF應用程序,我遇到了一個奇怪的綁定問題,感覺就像我失去了一些東西。WPF MVVM綁定到用戶控件的DependencyProperty不工作
我有一個用戶控件(PluginsTreeView),它有一個ViewModel(PluginsViewModel)來驅動它。 PluginsTreeView公開一個類型爲string(DocumentPath)的公共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!
}
....
}
與史努比亂搞,我看到,從XAML「從XAML」的值並使其進入財產,但我在PluginsTreeView設置方法仍然沒有被擊中。我在那裏作爲一個調試工具的消息框不會彈出,除非從MainWindow代碼隱藏設置值。
我想我已經找到了我自己的問題的答案,以防其他人遇到此問題。顯然你不應該爲這些屬性添加任何邏輯,因爲只有在你從代碼設置屬性時纔會調用它們。如果從XAML設置屬性,則直接調用SetValue()方法。 DependencyProperty.Register(「DocumentPath」,typeof(字符串),typeof(PluginsTreeView),新的FrameworkPropertyMetadata(「初始值」,OnValueChanged)註冊一個回調方法,現在工作得很好:public static readonly DependencyProperty DocumentPathProperty = );' – genus
這是正確的,你應該把它作爲你的問題的答案。或者,也許刪除你的問題,因爲我確定它已經被問及幾次了。 – Alan