【问题标题】:Replace a control within a user control through dependency property通过依赖属性替换用户控件中的控件
【发布时间】:2011-06-29 18:10:39
【问题描述】:

我做了一个简单的项目来说明我的问题。我有一个包含一个按钮和一个矩形的用户控件('ButtonPod'):

<UserControl x:Class="SilverlightDependencyProp.ButtonPod"
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">
    <Rectangle Fill="Blue" />
    <Button x:Name="ButtonOnPage" Margin="50" Content="Old button content" />
</Grid>

</UserControl>

我想在整个应用程序中使用此用户控件,但我需要更改中间的按钮。我需要控制 Button 的所有属性,所以我不想只公开像“ButtonText”或“ButtonSize”这样的 DependencyProperties - 我宁愿在使用控件时定义整个 Button。所以我像这样设置了一个依赖属性('CenterButton'):

    public Button CenterButton
    {
        get { return (Button)GetValue(CenterButtonProperty); }
        set { SetValue(CenterButtonProperty, value); }
    }

    public static readonly DependencyProperty CenterButtonProperty =
        DependencyProperty.Register("CenterButton", typeof(Button),
        typeof(ButtonPod), new PropertyMetadata(
        CenterButtonChanged));

    private static void CenterButtonChanged(DependencyObject d,
      DependencyPropertyChangedEventArgs e)
    {
        var pod = d as ButtonPod;
        pod.ButtonOnPage = e.NewValue as Button;
    }

然后我尝试在我的 MainPage.xaml 上定义“CenterButton”,在我的用户控件中:

<Grid x:Name="LayoutRoot" Background="White">
    <local:ButtonPod Width="200" Height="200">
        <local:ButtonPod.CenterButton>
            <Button Content="New button content" />   
        </local:ButtonPod.CenterButton>
    </local:ButtonPod>
</Grid>

但是当我加载应用程序时,我看到的只是一个显示“旧按钮内容”的按钮——为什么我的按钮没有被替换?逐步进行,我可以看到 DependencyProperty 被命中并且 'ButtonOnPage' 属性被设置,但视觉树没有更新。有什么想法吗?

【问题讨论】:

    标签: silverlight dependency-properties visual-tree


    【解决方案1】:

    设置命名元素不会替换它。您想命名父级并将子级添加到其中(替换现有的子级)。

    【讨论】:

    • 正确,但不会用新按钮替换 (通过 pod.ButtonOnPage = e. NewValue as Button;) 影响可视化树?该属性只是设置新按钮的方式..或者我认为。
    • 谢谢——问题是 x:Name 只是引用了页面上的内容,您无法更改.. 基本上就像没有集合的 get 一样。感谢您的帮助。
    • @Nick Bradley:如果您查看生成的设计器代码,您会发现每个命名元素都有一个成员。这些连接到 Xaml,但也只是属性。通过设置命名属性,您只是替换了一个类成员,而不是将其连接到可视化树。我猜这些属性都应该被标记为“只读”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2021-05-14
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多