gpt4 book ai didi

c# - 更改 UserControl 中的值时,通过 UserControl 的绑定(bind)中断

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:02 26 4
gpt4 key购买 nike

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

window

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>

最佳答案

您在 UserControl 中创建的 DependencyProperty 默认情况下不会更新绑定(bind)源。

因此,当您通过 UserControls slider 更改 Value 时,绑定(bind)不会自动更改 Window 中的 Value >.

要修复它,您可以设置 Mode Binding 的属性到 TwoWay

这将确保对绑定(bind)目标(UserControl 中的Value)的更改将更新绑定(bind)源(Value in 窗口)

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

关于c# - 更改 UserControl 中的值时,通过 UserControl 的绑定(bind)中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com