Skip to main content
 首页 » 编程设计

c#之WPF 文本框和浏览文件之是否有更优雅的解决方案

2024年02月23日23haluo1

我有一个简单的文本框+文件对话框场景。文本框绑定(bind)到集合中的对象。我想选择文件并让它填充文本框,这反过来将更新绑定(bind)的对象属性。设法将文件名放入文本框,但随后文本框绑定(bind)没有触发,因为它没有检测到更改。我必须添加一个 focus() 更改来触发更新。有没有更好的办法?

<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(); 
    } 
}    

请您参考如下方法:

只需直接设置 View 模型属性 FlexString1。

绑定(bind)将确保 UI 得到正确更新。

您还可以将浏览对话框放在命令上,这样它就可以在 View 模型而不是 View 中完成。