【问题标题】:Binding through UserControl breaks when changing values in UserControl更改 UserControl 中的值时,通过 UserControl 绑定会中断
【发布时间】:2014-01-04 23:01:21
【问题描述】:

我有以下 UserControl 和 Window,每个都有一个滑块,应该绑定到同一个属性,这里在窗口中定义为依赖属性。当我在主窗口中移动滑块时,UserControl 中的滑块随之而来。如果我触摸 UserControl 中的滑块,则主窗口中的滑块不会更改并且绑定中断,因为 UserControl 中的滑块将不再跟随主窗口中的滑块。主窗口中的滑块不会松开它的绑定。我做错了什么?

窗户

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(float), typeof(Window1),
                                    new FrameworkPropertyMetadata());

    public float Value {
        get { return (float)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
}

<Window
    x:Class="UserControlBindingDemo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:user="clr-namespace:UserControlBindingDemo"
    Title="UserControlBindingDemo"
    Height="300"
    Width="300"
    x:Name="wndw">
    <Grid>
        <Slider
            Grid.Column="0"
            Grid.Row="0"
            Value="{Binding Path=Value, ElementName=wndw}" />
        <user:UserControl1
            Grid.Column="0"
            Grid.Row="1"
            Value="{Binding Path=Value, ElementName=wndw}" />
    </Grid>
</Window>

用户控件

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(float), typeof(UserControl1),
                                    new FrameworkPropertyMetadata());

    public float Value {
        get { return (float)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
}

<UserControl x:Class="UserControlBindingDemo.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="uc">
    <Grid>
        <Slider
            Value="{Binding Path=Value, ElementName=uc}" />
    </Grid>
</UserControl>

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    你在UserControl中创建的DependencyProperty默认不更新绑定源。

    因此,当您通过UserControls 滑块更改Value 时,绑定不会自动更改Window 中的Value

    要修复它,您可以将BindingMode 属性设置为TwoWay

    这将确保对绑定目标(UserControl 中的Value)的更改将更新绑定源(Window 中的Value

    <user:UserControl1
        Grid.Column="0"
        Grid.Row="1"
        Value="{Binding Path=Value, ElementName=wndw, Mode=TwoWay}" />
    

    【讨论】:

    • 谢谢你,说的很清楚。我还找到了默认获取DependencyProperty 使TwoWay Bindings 的方法。为此,我编写了一个私有静态方法,返回 BindsTwoWayByDefault 选项设置为 trueFrameworkPropertyMetadata 实例,我在 Register 调用中使用。
    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 2011-05-18
    • 2016-01-21
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多