我是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变量?
感谢您的协助!
您需要将窗口的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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句