我有一個簡單的文本框+文件對話框場景。文本框綁定到colourection中的對象。我想選擇文件並使其填充文本框,這又將更新綁定的對象屬性。設法讓文件名進入文本框,但是文本框綁定沒有被觸發,因爲它沒有檢測到變化。我不得不添加焦點()更改來觸發更新。有沒有更好的辦法?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();
}
}