wpf - 将文本框的文本属性绑定(bind)到 MainWindow-WPF 上定义的变量

标签 wpf data-binding

我是 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/

相关文章:

wpf - 如何设置实时图表的标签颜色?

c# - 如何将数据表绑定(bind)到 wpf 可编辑组合框 : selectedItem showing System. Data.DataRowView

json - 如何将复杂对象映射到简单字段

.net - WPF 中的依赖属性和附加属性有什么区别?

.net - 如何使用 PRISM 创建 XAML 启动屏幕

c# - 将标签内容绑定(bind)到嵌套类中的值而不是 Datacontext

c# - 从附加属性设置样式中的 WPF MenuItem 图标

wpf - 重新绑定(bind)到 WPF Datagrid 的 Datacontext

WPF 4.0 对 DataGrid 上的 ContextMenu 进行数据绑定(bind)

wpf - 为什么 Silverlight/WP7 上的 NavigationService 在类上使用字符串?