我是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绑定到outputFolderPath变量?
谢谢你的帮助!
答案 0 :(得分:1)
您需要将窗口的DataContext设置为 this ,以便在XAML中访问您的属性,然后绑定到该属性。由于您不绑定DependencyProperty,您应该通知绑定属性已更改,这可以通过在Window中实现INotifyPropertyChanged接口来完成。 我提供了示例代码来展示这个概念 但这非常难看,更好的是使用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>