2011-10-26 8 views
1

私はシンプルなテキストボックス+ファイルダイアログシナリオを持っています。テキストボックスは、colooection内のオブジェクトにバインドされます。私は、ファイルを選択して、それがバインドされたオブジェクトのプロパティを更新するテキストボックスにデータを入力したい。テキストボックスにファイル名を取得することができましたが、テキストボックスのバインディングは変更を検出しなかったため起動しませんでした。私はfocus()の変更を追加して更新をトリガーする必要がありました。そこには良い方法がありますか?WPFのテキストボックスとブラウズファイル - より洗練されたソリューションはありますか?

<TextBox Text="{Binding Path=FlexString1,Mode=TwoWay}" 
     Height="23" 
     HorizontalAlignment="Left" 
     Margin="10" Name="textPath" 
     VerticalAlignment="Top" 
     Width="236" /> 
<Button Height="25" 
     HorizontalAlignment="Left" 
     Margin="0" 
     Name="btnBrowseFile" 
     Padding="1" VerticalAlignment="Top" 
     Width="45" Click="btnBrowseFile_Click"> 
    <TextBlock FontSize="10" 
      FontWeight="Normal" 
      Foreground="#FF3C3C3C" 
      Text="Browse" 
      TextWrapping="Wrap" /> 
</Button> 

private void btnBrowseFile_Click(object sender, RoutedEventArgs e) 
{ 
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
    //dlg.FileName = "Document"; // Default file name 
    //dlg.DefaultExt = ".txt"; // Default file extension 
    //dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog(); 

    // Process open file dialog box results 
    if (result == true) 
    { 
     // Open document 
     TextBox path = (TextBox)(((FrameworkElement)sender).Parent as FrameworkElement).FindName("textPath"); 
     path.Text = dlg.FileName; 
     path.Focus(); //these 2 lines force the binding to trigger 
     ((Button)sender).Focus(); 
    } 
} 

答えて

2

ビューモデルプロパティFlexString1を直接設定するだけです。

バインディングによって、UIが正しく更新されます。

ビューに表示するのではなく、ビューモデル内からコマンドを実行するようにブラウズダイアログを配置することもできます。

2

TextBoxのデフォルトの更新はLostFocusです。代わりにPropertyChangedに変更してみてください。

<TextBox Text="{Binding Path=FlexString1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> 
関連する問題