用户控件绑定因值更新而丢失,这在标准文本框控件中不会发生

时间:2018-07-31 08:20:49

标签: c# wpf xaml binding user-controls

我在绑定用户控件时遇到问题。

这是我的用户控件:

UserControl1.xaml

<UserControl x:Class="WpfApp1.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-ompatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d" 
    x:Name="usercontrol"
    d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <TextBox Text="{Binding HmiField, ElementName=usercontrol}"/>
    </Grid>
</UserControl>

UserControl1.xaml.cs

namespace WpfApp1
{
    public partial class UserControl1 : UserControl
    {

        public double HmiField
        {
            get { return (double)GetValue(HmiFieldProperty); }
            set { SetValue(HmiFieldProperty, value); }
        }
        public static readonly DependencyProperty HmiFieldProperty =
            DependencyProperty.Register("HmiField", typeof(double), typeof(UserControl1));

        public UserControl1()
        {
            InitializeComponent();
        }
    }
}

这是主窗口:

MainWindow.xaml

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        DataContext="{Binding Md, RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="450" Width="800">
    <UniformGrid>
        <Button Content="{Binding Prop1}" Click="Button_Click"/>
        <Label Content="{Binding Prop1}"/>
        <TextBox Text="{Binding Prop1}"/>
        <local:UserControl1 HmiField="{Binding Prop1}"/>
    </UniformGrid>
</Window>

MainWindow.xaml.cs

namespace WpfApp1
{

    public class tMd: INotifyPropertyChanged
    {
        #region Interfaccia INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }

        #endregion

        private double prop1;
        public double Prop1 { get
            {
                return prop1;
            }
            set
            {
                if (prop1 != value)
                {
                    prop1 = value;
                    NotifyPropertyChanged("Prop1");
                }
            }
        }
    }

    public partial class MainWindow : Window
    {

        public tMd Md
        {
            get { return (tMd)GetValue(MdProperty); }
            set { SetValue(MdProperty, value); }
        }
        public static readonly DependencyProperty MdProperty =
            DependencyProperty.Register("Md", typeof(tMd), typeof(MainWindow), new PropertyMetadata(new tMd()));

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Md.Prop1 = 1234.5678;
        }
    }
}

我发现了一些类似的问题:

How do I change TextBox.Text without losing the binding in WPF?

WPF: Binding is lost when bindings are updated

WPF Textbox TwoWay binding in datatemplate not updating the source even on LostFocus

但是我无法完全理解正在发生的事情:为什么标准文本框可以按预期运行,而我的用户控件却无法运行?

或更妙的是:有没有办法让我的usercontrol可以处理文本框的行为?

2 个答案:

答案 0 :(得分:1)

绑定必须是双向的,可以明确设置

<local:UserControl1 HmiField="{Binding Prop1, Mode=TwoWay}"/>

或默认情况下隐式:

public static readonly DependencyProperty HmiFieldProperty =
    DependencyProperty.Register(
        nameof(HmiField), typeof(double), typeof(UserControl1),
        new FrameworkPropertyMetadata(
            0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

文本框的Text属性如上所示进行注册,即使用BindsTwoWayByDefault标志进行注册。


在UserControl的XAML的TextBox绑定中,您可能还希望在用户键入时更新source属性(而不是仅失去焦点):

<TextBox Text="{Binding HmiField,
                ElementName=usercontrol,
                UpdateSourceTrigger=PropertyChanged}"/>

,或者没有其他无用的usercontrol字段:

<TextBox Text="{Binding HmiField,
                RelativeSource={RelativeSource AncestorType=UserControl}
                UpdateSourceTrigger=PropertyChanged}"/>

答案 1 :(得分:0)

您的Prop1会在更改时通知您,但您尚未告诉您绑定以触发该通知。 尝试在绑定中包含UpdateSourceTrigger = PropertyChanged