c# - 与 UserControl 的双向绑定(bind)

标签 c# silverlight xaml user-controls binding

我正在尝试在我创建的 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/

相关文章:

c# - 是否清除包含 ComObject 的列表,在 C# 中释放所有这些对象?

c# - "An unsecured or incorrectly secured fault was received from the other party"

c# - Service Fabric 无状态服务行为

c# - 将 ObservableCollection<XElement> 数据绑定(bind)到 ListBox?

WPF 默认主题和自定义样式不能一起工作

xaml - ContentDialog 不滚动

c# - Object.Equals(obj1, obj2) vs obj1.Equals(obj2)?

c# - Visual Studio 2015 Silverlight Ria 服务项目引用

silverlight - 第一次单元测试(在 Silverlight 中)

c# - 使用 XamlReader.Parse() 从字符串读取 xaml 时使用转换器