【发布时间】: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