我正在尝试在我创建的 UserControl 上设置双向绑定(bind)。
当我在 Xaml 中使用控件时,会像这样设置 DataContext...
<uc:MyUserControl DataContext="{Binding Path=MyObject, Mode=TwoWay}" />
我的用户控件定义如下....
<UserControl x:Class="SilverlightApplication1.XText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding}"/>
</Grid>
</UserControl>
数据显示正确,但是如果我进行更改,我希望它使用 TwoWay 绑定(bind)进行更新。
我已经在下面尝试过,但是由于没有定义路径,它在运行时出错。
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding Mode=TwoWay}"/>
</Grid>
</UserControl>
关于如何让用户控件内部的控件双向绑定(bind)到 DataContext 有什么想法吗?
最佳答案
虽然您上面的( self 回答的)答案似乎可以解决问题,但我不禁认为这是一个问题域问题。我很难想一想为什么您首先要像那样直接绑定(bind),尤其是因为它让您无法控制数据发生的情况。
采取以下措施:
<UserControl
x:Class="SilverlightApplication1.XText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="UserControl"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding Path=Value, ElementName=UserControl, Mode=TwoWay}"/>
</Grid>
</UserControl>
然后在代码隐藏中:
public partial class XText
{
public static DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(string),
typeof(XText),
new FrameworkPropertyMetadata(null)
);
public string Value
{
get { return ((string)(base.GetValue(XText.ValueProperty))); }
set { base.SetValue(XText.ValueProperty, value); }
}
...
}
然后,当您准备好使用它时:
<uc:XText Value="{Binding Path=MyObject, Mode=TwoWay}" />
是的,它有更多代码,但它使您可以更好地控制 UserControl
中的 Value
发生的事情,并使使用此代码更简单 future 。
想法?
-道格
编辑:修复了几个拼写错误。
关于c# - 与 UserControl 的双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3470116/