我是 WPF 新手,我有用于打开文件夹浏览器对话框的文本框和按钮。
当用户选择文件夹时,我希望文本框将包含所选路径。
所以在 MainWindow 上我添加了两个变量:
public partial class MainWindow : Window
{
public string outputFolderPath { get; set; }
string reducedModelFolderPath { get; set; }
}
当用户选择文件夹路径(打开文件夹对话框后)时,我通过执行以下操作更新了这些变量(例如):
outputFolderPath = dialog.SelectedPath
在MainWindow.xaml中:
<TextBox x:Name="outputFolder" Width ="200" Height="30" Grid.Row="1" Grid.Column="1" Margin="5 10">
如何将 TextBox.Text 绑定(bind)到 outputFolderPath 变量?
感谢您的帮助!
最佳答案
您需要将窗口的 DataContext 设置为 this,以在 XAML 中访问您的属性,然后绑定(bind)到该属性。由于您没有绑定(bind)到 DependencyProperty,因此您应该通知您的绑定(bind)属性已更改,这可以通过在 Window 中实现 INotifyPropertyChanged 接口(interface)来完成。
我提供了示例代码来展示这个概念。
但这非常难看,最好使用 MVVM 模式来代替。
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public string outputFolderPath { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void Button_Click(object sender, RoutedEventArgs e)
{
outputFolderPath = "Some data";
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(outputFolderPath)));
}
}
MainWindow.xaml
<Window x:Class="simplest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:simplest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Click="Button_Click" Content="Go" />
<TextBox x:Name="outputFolder" Width ="200" Height="30" Grid.Row="1" Grid.Column="1" Margin="5 10" Text="{Binding outputFolderPath}"/>
</Grid>
</Window>
关于wpf - 将文本框的文本属性绑定(bind)到 MainWindow-WPF 上定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386329/