【问题标题】:UserControl: Can I set my own DependencyProperty in XAML?UserControl:我可以在 XAML 中设置我自己的 DependencyProperty 吗?
【发布时间】:2019-05-09 12:50:00
【问题描述】:

我希望能够做这样的事情:

.xaml.cs:

public partial class MyControl : UserControl
{
    public MyControl() => InitializeComponent();

    public static readonly DependencyProperty MyTemplateProperty = DependencyProperty.Register(
        "MyTemplate", typeof(DataTemplate), typeof(MyControl), new PropertyMetadata(default(DataTemplate)));

    public DataTemplate MyTemplate
    {
        get => (DataTemplate) GetValue(MyTemplateProperty);
        set => SetValue(MyTemplateProperty, value);
    }
}

.xaml:

<UserControl x:Class="MyControl"> <!-- etc. -->
    <Grid />

    <!-- does not compile-->
    <UserControl.MyTemplate>
        <DataTemplate />
    </UserControl.MyTemplate>
</UserControl>

但它不起作用。毫不奇怪,当您以 UserControl 开头元素名称时,编译器仅查找在 UserControl 本身上定义的属性。但是将元素名称更改为&lt;MyControl.MyTemplate&gt;(带有正确的命名空间前缀)也不起作用;在这种情况下,编译器会尝试将 MyTemplate 解释为附加属性。

除了在资源中定义值然后从代码隐藏中将其分配给属性之外,还有什么方法可以实现这一点?

【问题讨论】:

    标签: wpf xaml user-controls


    【解决方案1】:

    您可以通过样式设置属性:

    <UserControl ...>
        <UserControl.Style>
            <Style>
                <Setter Property="local:MyControl.MyTemplate">
                    <Setter.Value>
                        <DataTemplate />
                    </Setter.Value>
                </Setter>
            </Style>
        </UserControl.Style>
        ...
    </UserControl>
    

    【讨论】:

    • 好主意!但是为什么没有 TargetType?它似乎与一个工作正常......
    • @dlf 你的意思是TargetType="local:MyControl"?我的 XAML 设计器不喜欢这样。虽然它在运行时工作......
    • 我做了TargetType="{x:Type local:MyControl}",VS2017和R#都可以。
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    相关资源
    最近更新 更多