将依赖项属性从自定义类绑定到UI

时间:2015-04-11 21:37:41

标签: wpf c#-4.0

已经尝试了几乎一个洞一周来找到如何将自定义类(Elements)中的依赖项属性绑定到一个简单的文本框, 文本框内的文本每次发送特定数据时都必须更改,这是第一次发生,之后,文本框需要更新? 我已经尝试过每一个例子,但我无法实现我的目标,这是我的代码: 对于创建依赖项对象的类:

  public class Elements : DependencyObject
{

    public static DependencyProperty TextDataProperty = DependencyProperty.Register
        (
         "TextData",
         typeof(string),
         typeof(Elements),
         new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender)
        );

    public string TextData
    {
        get
        {
            return (string)GetValue(TextDataProperty);
        }
        set
        {
            SetValue(TextDataProperty, value);
        }
    }

    public void UpdateText(string sdata)
    {
        TextData = sdata;
    }
}

我在xaml中像这样引用这个类

  xmlns:local="clr-namespace:WpfApplication1"

并使用它:

<Window.Resources>
    <local:Elements x:Key="myElements" ></local:Elements>
</Window.Resources>

需要更新的文本框绑定到自定义类,如下所示:

 <TextBox 
        Height="23" 
        HorizontalAlignment="Left" 
        Margin="12,61,0,0" 
        Name="textBox1" 
        VerticalAlignment="Top" 
        Width="237" 
        Text="{Binding TextData, Source={StaticResource myElements}}"
             />

我做错了什么?请有人帮忙吗

1 个答案:

答案 0 :(得分:0)

从您的评论中:您正在

中创建一个新的Elements对象
Elements _elements = new Elements();
_elements.UpdateText(textBox2.Text); 

这不是

中用于绑定的对象
Text="{Binding TextData, Source={StaticResource myElements}}"

更改您的代码,以便它从Resources:

访问该对象
var elements = (Elements)Resources["myElements"];
elements.UpdateText(textBox2.Text);

然后你应该用TextBlock替换TextBox,因为你只想显示文本,但不希望用户编辑它。

您还应该了解MVVM设计模式以及它在WPF中的使用方式。有很多在线资源可用。

相关问题