【问题标题】:WPF UserControl with Binding Mode=OneWay绑定模式=OneWay 的 WPF 用户控件
【发布时间】:2015-08-14 03:19:57
【问题描述】:

我正在尝试制作一个带有可绑定属性的示例 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”。如果“MainWindow.xaml”文件中的绑定设置为“TwoWay”,用户控件会不断更新,但如果我使用“OneWay”绑定,那么用户控件会更新一次,然后“PropertyChanged” “MyDataObject”类实例的事件不会再次触发,因为它突然没有订阅者了。

为什么“OneWay”绑定被调用一次后就停止工作了? 哪些代码更改可以让“TwoWay”和“OneWay”绑定继续工作?

【问题讨论】:

  • 当您遇到任何Binding 问题时,您应该会看到在 Visual Studio 的输出窗口中显示了哪些错误...它们会告诉您问题所在。

标签: c# wpf xaml binding user-controls


【解决方案1】:

首先。

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

不啊啊啊啊啊啊!

从来没有。曾经。曾经。从代码隐藏设置您的DataContext。一旦你这样做了,你就会失去从你的父控件绑定到你的用户控件的依赖属性的神奇美感。换句话说,就是不要这样做。

这是你应该做的:

给你的UserControl 一个x: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)。

完成我之前提到的内容。有很多东西要学,但这只是一个开始。

【讨论】:

  • 对不起,我无法理解以“
  • 是的,我提供的代码只是示例。
  • 我将如何使用以“
  • 我不确定你在这里问什么。据我所知,用户控件中的所有元素都需要绑定到名为 Text 的依赖属性。
  • 我的用户控件中只有一个 TextBox,这是我想要绑定到“Text”依赖属性的唯一一个。然后我在那里有一个标签,但它可以保持未绑定。
【解决方案2】:

在我看来就像它的这一行:

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 或 TwoWay 绑定一起使用,并且您将观察到字符串的长度随着计时器的触发而增加。

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

【讨论】:

    猜你喜欢
    • 2011-07-21
    • 1970-01-01
    • 2013-06-06
    • 2011-02-22
    • 2014-01-14
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多