【问题标题】:The databinding of a usercontrol doesn't update the source model用户控件的数据绑定不会更新源模型
【发布时间】:2015-07-21 00:05:38
【问题描述】:

我正在尝试实现一个包含占位符文本的自定义文本框。我的模型的“名字”属性的内容按预期显示在文本框中。我遇到的问题是当我更改文本框的文本时,它没有在源模型中更新。这是为什么呢?

我尝试将绑定模式设置为“TwoWay”,但它并没有改变任何东西。是不是我做错了什么?

编辑:真傻!事实证明,我不得不将 Mode="TwoWay" 放在两个绑定上,而不仅仅是用户控件的绑定。我会尽快标记为已回答。

模型.cs

public class Student
{
    public string FirstName { get; set; }
}

MainWindow.xaml

<grid>
    <ui:prettyTextbox Text="{Binding FirstName}" PlaceholderText="#Enter your name">
</grid>

PrettyTextbox.xaml

<UserControl x:Name="prettyTextbox">
    <Grid>
        <TextBlock Text="{Binding Path=PlaceholderText, ElementName=prettyTextbox}"
                       Visibility="{Binding Path=Text, ElementName=prettyTextbox, Converter={StaticResource StringLengthToVisibilityConverter}}"/>
        <TextBox Text="{Binding Path=Text, ElementName=prettyTextbox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</UserControl>

PrettyTextbox.xaml.cs

public partial class PrettyTextbox : INotifyPropertyChanged
{
    public static readonly DependencyProperty PlaceholderTextProperty =
            DependencyProperty.Register("PlaceholderText", typeof (string),
                                        typeof(PrettyTextbox), new FrameworkPropertyMetadata(default(string)));

    public string PlaceholderText
    {
        get { return (string)GetValue(PlaceholderTextProperty); }
        set
        {
            SetValue(PlaceholderTextProperty, value);
            OnPropertyChanged();
        }
    }


    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string),
                                    typeof(PrettyTextbox), new FrameworkPropertyMetadata(default(string)));

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set
        {
            SetValue(TextProperty, value);
            OnPropertyChanged();
        }
    }

    public PrettyTextbox()
    {
        InitializeComponent();
    }

}

}

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    你忘了让 text 属性默认绑定两种方式,所以你需要改变这部分:

    <ui:prettyTextbox Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    

    或将文本属性的 FrameworkPropertyMetadata 更改为:

    new FrameworkPropertyMetadata
    {
        DefaultValue = null,
        BindsTwoWayByDefault = true
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 2023-04-02
      • 2010-12-12
      • 2017-11-13
      • 2010-11-29
      • 2013-02-03
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      相关资源
      最近更新 更多