如何将UserControl的自定义依赖项属性与嵌套控件的属性联系在一起?

时间:2013-11-13 08:07:03

标签: c# .net wpf

我有一个UserControl,其中包含三个TextBlock控件。我想在UserControl中实现三个自定义属性。类似的东西:

public partial class MyControl: UserControl
{
    ...
    public String Title
    {
        get { return this.textBlock1.Text; }
        set { this.textBlock1.Text = value; }
    }

    public String Units
    {
        get { return this.textBlock2.Text; }
        set { this.textBlock2.Text = value; }
    }

    public String Data
    {
        get { return this.textBlock3.Text; }
        set { this.textBlock3.Text = value; }
    }
}

如果我想对这些属性使用绑定功能,我必须将它们作为依赖项属性实现。我对吗?但我不知道怎么办。

2 个答案:

答案 0 :(得分:0)

依赖属性的代码:

  public string Title
  {
    get { return (string)this.GetValue(TitleProperty); }
    set { this.SetValue(TitleProperty, value); } 
  }

  public static readonly DependencyProperty TitleProperty = 
                 DependencyProperty.Register("Title",
                                             typeof(string),
                                             typeof(MyControl),
                                             new PropertyMetadata(null));

在xaml中绑定:

<TextBlock Text="{Binding Title,
                  RelativeSource={RelativeSource FindAncestor,
                                  AncestorType={x:Type yourXmlns:MyControl}}"/>

答案 1 :(得分:0)

这是正确的。绑定到依赖项属性非常简单。理解我将建议通过MSDN查看的机制。但是,要回答您的问题,请提供注册到用户控件的静态依赖项属性。然后你的getters \ setters引用该属性。

以下是依赖项属性的示例行。

/// <summary>
/// Provides a bindable text property to the user control
/// </summary>
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata("", onTextPropertyChanged));

/// <summary>
/// optional static call back handler when the property changed
/// </summary>
/// <param name="o"></param>
/// <param name="e"></param>
static void onTextPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    var obj = o as UserControl1;
    if (obj == null)
        return;

    //TODO: Changed...
}

/// <summary>
/// Gets \ sets the text
/// </summary>
public string Text
{
    get { return (string)this.GetValue(TextProperty); }
    set
    {
        if (this.Text != value)
            this.SetValue(TextProperty, value);
    }
}

以上很简单。我们将依赖属性TextProperty注册到UserControl1,此属性是字符串的类型,其默认值为“”(如属性元数据中所述)。如果您希望在属性发生更改后执行其他步骤,我还提供了一个静态回调处理程序。

然后,您将看到Text属性使用GetValue()SetValue()方法来获取和设置Text属性的值。

更新:绑定到XAML中的子元素。

此更新旨在说明如何使用上述TextProperty进行绑定。

Usercontrol1.Xaml。这是UserControl1的XAML。

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" FontWeight="Bold" Content="Text" VerticalAlignment="Center" />
        <TextBox Text="{Binding Text, Mode=TwoWay}" Grid.Column="1" VerticalAlignment="Center" Padding="4" />
    </Grid>
</UserControl>

我的主窗口视图模型(实现INotifyPropertyChanged)

public class MainWindowModel : INotifyPropertyChanged
{
    /// <summary>
    /// the text
    /// </summary>
    string myProperty = "This is the default text";

    /// <summary>
    /// Gets \ sets the text
    /// </summary>
    public string MyProperty
    {
        get { return this.myProperty;  }
        set
        {
            if (this.MyProperty != value)
            {
                this.myProperty = value;
                this.OnPropertyChanged("MyProperty");
            }
        }
    }

    /// <summary>
    /// fires the property changed event
    /// </summary>
    /// <param name="propertyName"></param>
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    /// the property changed event
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;
}

MainWindow.Xaml。将text属性绑定到视图模型

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ctrl="clr-namespace:WpfApplication1"
        Name="Window1"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <ctrl:MainWindowModel />
    </Window.DataContext>
    <Grid>
        <ctrl:UserControl1 Text="{Binding Path=DataContext.MyProperty, Mode=TwoWay, ElementName=Window1}" />
    </Grid>
</Window>