绑定模式为单向的WPF用户控件

本文关键字:WPF 用户 控件 模式 绑定 | 更新日期: 2023-09-27 17:52:13

我正在尝试制作一个具有可绑定属性的示例WPF用户控件(也许它会更好地说"开发人员控件")。我的代码由以下文件组成:

----- MainWindow.xaml -----
<Window x:Class="Test_Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:testBinding="clr-namespace:Test_Binding"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <testBinding:MyLabelledTextBox x:Name="MLTB" LabelText="My custom control: MyLabelledTextBox" Text="{Binding StringData, Mode=OneWay}" />
    </StackPanel>
</Window>
----- MainWindow.xaml.cs -----
using System.Windows;
namespace Test_Binding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.DataContext = new MyDataObject();
            this.InitializeComponent();
        }
    }
}
----- MyDataObject.cs -----
using System.Runtime.CompilerServices; // CallerMemberName
using System.ComponentModel; // INotifyPropertyChanged
namespace Test_Binding
{
    public class MyDataObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string stringData;
        public string StringData
        {
            get { return this.stringData; }
            set
            {
                if (value != this.stringData)
                {
                    this.stringData = value;
                    this.OnPropertyChanged();
                }
            }
        }
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public MyDataObject()
        {
            System.Timers.Timer t = new System.Timers.Timer();
            t.Interval = 10000;
            t.Elapsed += t_Elapsed;
            t.Start();
        }
        private void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.StringData = ((this.StringData ?? string.Empty).Length >= 4 ? string.Empty : this.StringData + "*");
        }
    }
}
----- MyLabelledTextBox.xaml -----
<UserControl x:Class="Test_Binding.MyLabelledTextBox"
             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-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
  <StackPanel Background="Yellow">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.5*" />
            <ColumnDefinition Width="0.5*" />
        </Grid.ColumnDefinitions>   
        <Label x:Name="MLTBLabel" Grid.Row="0" Grid.Column="0" />
        <TextBox x:Name="MLTBTextBox" Grid.Row="0" Grid.Column="1" Background="Yellow" Text="{Binding Text, Mode=TwoWay}" />
    </Grid>
  </StackPanel>
</UserControl>
----- MyLabelledTextBox.xaml.cs -----
using System.Windows;
using System.Windows.Controls;
namespace Test_Binding
{
    /// <summary>
    /// Interaction logic for MyLabelledTextBox.xaml
    /// </summary>
    public partial class MyLabelledTextBox : UserControl
    {
        public static readonly DependencyProperty LabelTextProperty =
            DependencyProperty.Register("LabelText", typeof(string), typeof(MyLabelledTextBox),
            new PropertyMetadata(string.Empty, MyLabelledTextBox.LabelTextPropertyChanged));
        public string LabelText
        {
            get { return (string)this.GetValue(MyLabelledTextBox.LabelTextProperty); }
            set { this.SetValue(MyLabelledTextBox.LabelTextProperty, value); }
        }
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(MyLabelledTextBox),
            new PropertyMetadata(string.Empty, MyLabelledTextBox.TextPropertyChanged));
        public string Text
        {
            get { return (string)this.GetValue(MyLabelledTextBox.TextProperty); }
            set { this.SetValue(MyLabelledTextBox.TextProperty, value); }
        }
        public MyLabelledTextBox()
        {
            this.InitializeComponent();
            this.MLTBLabel.DataContext = this;
            this.MLTBTextBox.DataContext = this;
            this.MLTBTextBox.TextChanged += new TextChangedEventHandler(this.MLTBTextBox_TextChanged);
        }
        private void MLTBTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.Text = this.MLTBTextBox.Text; // transfer changes from TextBox to bindable property (bindable property change notification will be fired)
        }
        private static void LabelTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((MyLabelledTextBox)d).MLTBLabel.Content = (string)e.NewValue; // transfer changes from bindable property to Label
        }
        private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((MyLabelledTextBox)d).MLTBTextBox.Text = (string)e.NewValue; // transfer changes from bindable property to TextBox
        }
    }
}

有一个"MyDataObject"类的实例,其属性为"StringData",它使用计时器定期修改。我的用户控件被绑定到它的属性"StringData"。如果在"主窗口"中绑定。xaml "文件被设置为" two - way ",用户控件不断更新,但如果我使用" one - way "绑定,则用户控件被更新一次,然后" MyDataObject "类实例的" PropertyChanged "事件不再触发,因为突然它没有订阅者。

为什么"OneWay"绑定在被调用一次后停止工作?怎样的代码变更才能使"two - way"answers"one - way"绑定保持工作?

绑定模式为单向的WPF用户控件

第一。

this.MLTBLabel.DataContext = this;
this.MLTBTextBox.DataContext = this;

Noooooooooooooooo !

从来没有。永远。永远。从代码后置设置DataContext。一旦这样做,您就失去了从父控件绑定到用户控件的依赖项属性的神奇之美。换句话说,就是不要这样做。

你应该这样做:

给你的UserControlx:Name

<UserControl ...
    x:Name="usr">

把你的UserControl的依赖属性绑定到你的元素上,像这样:

<TextBlock Text="{Binding MyDependencyProperty, ElementName=usr}" ... />

将你的UserControl的DataContext属性绑定到你的元素,像这样:

<TextBlock Text="{Binding MyDataContextProperty}"/>

使用此方法将允许您在MainWindow中设置UserControlDataContext,但仍然能够在UserControl中绑定到UserControl的依赖属性。如果你在后台代码中设置了UserControl的DataContext,你将无法绑定到你的依赖属性。

现在,进入你的实际问题。

所有这些:

private void MLTBTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        this.Text = this.MLTBTextBox.Text; // transfer changes from TextBox to bindable property (bindable property change notification will be fired)
    }
    private static void LabelTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((MyLabelledTextBox)d).MLTBLabel.Content = (string)e.NewValue; // transfer changes from bindable property to Label
    }
    private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((MyLabelledTextBox)d).MLTBTextBox.Text = (string)e.NewValue; // transfer changes from bindable property to TextBox
    }

算了吧。看来你是想回避我之前说过的那些错误。

你应该绑定到你的依赖属性:

<Label Grid.Row="0" Grid.Column="0" Text="{Binding Text, ElementName=usr}"/>

另一个问题是,在你的MainWindow中,你在你的UserControl上使用绑定。

Text="{Binding StringData, Mode=OneWay}"

现在,由于您已经在代码隐藏中设置了DataContext。这实际上是在说:

从当前控件的DataContext绑定到StringData

在你的情况下,是一个完全不同的绑定从你的MainWindow DataContext。(因为你已经在UserControl中显式地设置了DataContext)。

浏览一下我前面提到的内容。还有很多东西要学,但这只是个开始。

在我看来是这样的:

this.StringData = ((this.StringData ?? string.Empty).Length >= 4 ? string.Empty : this.StringData + "*");
    }

第一次定时器触发时,this.StringData为空,所以'??'返回string.Empty。然后检查长度是否>= 4。它不是,所以它将this.StringData从null设置为string.Empty。由于属性仅在更改时更新,因此INotifyPropertyChanged触发一次。

第二次,我们从string.Empystring.Empty,所以INotifyPropertyChanged没有触发,因为没有变化。

本质上,定时器正在触发,但this.StringData现在卡在string.Empty上,这意味着INotifyPropertyChanged忽略了它。这是有道理的——如果属性实际上没有改变,为什么WPF运行时要把c#属性的更新推到GUI上呢?这只会让事情慢下来,没有任何好处。

如果使用双向绑定,这一切都会改变。如果this.StringData被设置为长度为4个字符或更多,那么它就像一匹赛马:它将每10秒执行代码,在它后面附加另一个"*"。

因此,如果您在启动时将this.StringData设置为"****",它将与单向或双向绑定一起工作,并且您将观察到随着计时器触发字符串的长度增加。

当然,如果设置为OneWay binding,字符串将只是连续添加一个*,并且它不会响应用户输入。我认为OneWayOneWayFromSource的简写,因此c#属性的更改将被推入XAML,但XAML的任何更改都不会被推回c#。