コード ビハインドからデータを入力する WPF ウィンドウに TextBox があります (ユーザーが OpenFileDialog.
TextBox.Text は ViewModel クラスの String プロパティにバインドされていますが、テキストが TextBox.Text に設定されている場合、プロパティは設定されません。
TextBox に入力すると、プロパティが入力されるため、コードを介して値を設定したときではなく、ユーザー入力中にイベントが発生するか、何かが発生する必要があります。
適切にバインドするために欠けているステップは何ですか?
また、プロパティの set メソッドは、プロパティまたは UI が変更されたときに呼び出されることを意図していますか? または両方?UI を変更すると set メソッドが呼び出され、PropertyChanged イベントが発生して UI が更新される場合、このループが永遠に停止するのは何ですか?
(プロパティを直接設定できることはわかっていますが、バインディングについての理解が不足していると感じており、これがいくつかのギャップを埋めるのに役立つことを願っています。)
私のサンプルコード:
<Window x:Class="ConfigurationViewer.ViewerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ConfigurationViewer"
Title="Configuration Viewer" Height="512" Width="714" >
<Window.DataContext>
<local:TaskViewModel x:Name="_model"/>
</Window.DataContext>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="Configuration file" Margin="2" VerticalAlignment="Center" />
<TextBox Height="29" Margin="2" Name="textFilePath" Width="277" Text="{Binding Path=ConfigurationPath}" />
<Button Content="Browse ..." Margin="2" Name="buttonBrowseFile" Width="98" Click="buttonBrowseFile_Click" />
<Button Content="Open" Margin="2" Name="buttonOpenFile" Width="98" Click="buttonOpenFile_Click" />
</StackPanel>
</DockPanel>
</Window>
public partial class ViewerWindow : Window
{
public ViewerWindow()
{
InitializeComponent();
}
private void buttonBrowseFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Multiselect = false;
openDialog.InitialDirectory = textFilePath.Text;
Nullable<Boolean> ok = openDialog.ShowDialog();
if (ok == true)
{
textFilePath.Text = openDialog.FileName;
}
}
private void buttonOpenFile_Click(object sender, RoutedEventArgs e)
{
}
}
public class TaskViewModel : INotifyPropertyChanged
{
private String _configurationPath = String.Empty;
public String ConfigurationPath
{
get { return _configurationPath; }
set
{
_configurationPath = value;
OnPropertyChanged("ConfigurationPath");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String prop)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(prop);
handler(this, e);
}
}
}