我有以下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>
UserControl
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>
答案 0 :(得分:0)
您在DependencyProperty
中创建的UserControl
默认情况下不会更新绑定的来源。
因此,当您通过Value
滑块更改UserControls
时,绑定不会自动更改Value
中的Window
。
要解决此问题,您可以将Binding
的{{3}}属性设置为TwoWay
。
这将确保更改绑定目标(Value
中的UserControl
)将更新绑定源(Value
中的Window
)
<user:UserControl1
Grid.Column="0"
Grid.Row="1"
Value="{Binding Path=Value, ElementName=wndw, Mode=TwoWay}" />