私は自分の WPF アプリを構築するための MVVM アプローチに固執しようとしていますが、奇妙なバインディングの問題が発生しており、何かが足りないように感じています。
ViewModel (PluginsViewModel) を駆動するユーザー コントロール (PluginsTreeView) があります。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 のコード ビハインドから設定されない限りポップしません。