在UserControl中暴露WPF DependencyProperty?

时间:2010-11-15 01:23:02

标签: wpf dependency-properties argument-passing

我有一个UserControl,我想要一些自定义参数“radius”(double)和“contentSource”(string [])。

我的UserControl由几个嵌套控件组成:

<UserControl ...>
<Grid>
    <my:Menu ...>
        <my:Button>
        </my:Button>
        <my:Button>
        </my:Button>
        <my:Button>
        </my:Button>
    </my:Menu ...>
</Grid>

我正试图用以下方法公开参数:

    public double Rad
    {
        get { return (double)GetValue(RadProperty); }
        set { SetValue(RadProperty, value); }
    }
    public static readonly DependencyProperty RadProperty =
        DependencyProperty.Register(
            "Radius",
            typeof(double),
            typeof(Menu));

    public String[] DataSource
    {
        get { return (String[])GetValue(DataSourceProperty); }
        set { SetValue(DataSourceProperty, value); }
    }
    public static readonly DependencyProperty DataSourceProperty =
        DependencyProperty.Register(
            "DataSource",
            typeof(String[]),
            typeof(Menu));

然而,似乎有两个问题,“string []”参数似乎导致崩溃,但大多数情况下,我根本无法设置“Radius”属性。我需要做些什么来公开参数吗?

1 个答案:

答案 0 :(得分:2)

您是如何尝试访问这些值的?我已将您的代码复制到UserControl中,它似乎工作正常。您是否为要从中访问这些值的对象设置了DataContext?

这是我的测试代码,可能有所帮助:

 public partial class uc : UserControl
{
    public uc()
    {
        InitializeComponent();

        this.DataContext = this;
        this.DataSource = new string[] { "hello","There" };
        this.Rad = 7;
    }
    public String[] DataSource
    {
        get { return (String[])GetValue(DataSourceProperty); }
        set { SetValue(DataSourceProperty, value); }
    }
    public static readonly DependencyProperty DataSourceProperty =
        DependencyProperty.Register(
            "DataSource",
            typeof(String[]),
            typeof(uc));

    public double Rad
    {
        get { return (double)GetValue(RadProperty); }
        set { SetValue(RadProperty, value); }
    }
    public static readonly DependencyProperty RadProperty =
        DependencyProperty.Register(
            "Radius",
            typeof(double),
            typeof(uc));

}

和XAML:

<UserControl x:Class="WpfApplication18.uc"
             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" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Path=DataSource[0]}"></TextBox>
            <TextBox Text="{Binding Path=DataSource[1]}"></TextBox>
            <TextBox Text="{Binding Path=Radius}"></TextBox>
            <TextBox Text="{Binding Path=Radius}"></TextBox>
        </StackPanel>
    </Grid>
</UserControl>