【问题标题】:C#: Binding textbox to object attributeC#:将文本框绑定到对象属性
【发布时间】:2018-11-16 07:56:48
【问题描述】:

我是对象绑定的新手,但我无法成功。

我有一个带有以下文本框的 xaml 窗口:

<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0" DataContext="{Binding currentproj}">
<Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<TextBox Grid.Row="0" Grid.Column="2" x:Name="txt_localdir"  Height="25" TextWrapping="Wrap" Width="247" IsEnabled="False" Text="{Binding Path=Localdir, UpdateSourceTrigger=PropertyChanged}"/>

在主窗口的cs代码中,我定义了我的Project类的一个实例,叫做currentproj,如下:

public partial class MainWindow : Window{
Project currentproj;

public MainWindow()
{            
    currentproj = new Project();
    InitializeComponent();
}}

项目类(在 Project.cs 文件中定义)如下:

公共部分类项目:组件,INotifyPropertyChanged { 公共事件 PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

private string _localdir;
public string Localdir
{
    get { return _localdir; }
    set
    {
        if (value != _localdir)
        {
            _localdir = value;
            NotifyPropertyChanged("Localdir");
        }
    }
}

public Project()
{
    InitializeComponent();
}

public Project(IContainer container)
{
    container.Add(this);

    InitializeComponent();
}}

但是,即使我将 textbox.text 属性绑定到 currentproj 对象的 Localdir 路径,文本框也永远不会更新。当我设置 Localdir 的值时,我看到 PropertyChanged 事件始终为空,但我不明白为什么。

【问题讨论】:

  • 您是否尝试过在 XAML 中的 Binding 中设置 Mode=TwoWay

标签: c# binding


【解决方案1】:

数据绑定适用于 DataContext。 Grid 的 DataContext 设置不正确,应该删除。

所以网格定义应该是:

<Grid x:Name="gr_main" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="180,65,0,0">

将 Window DataContext 设置为 currentProj 是通过以下方式完成的:

public partial class MainWindow : Window{
Project currentproj;

public MainWindow()
{            
    currentproj = new Project();
    DataContext = currentproj;
    InitializeComponent();
}}

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2019-09-23
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多