【问题标题】:Exposing internal properties of objects in WPF在 WPF 中公开对象的内部属性
【发布时间】:2012-03-09 15:56:56
【问题描述】:

我有以下用户控件

<UserControl 
           x:Class="MyUserControl"
           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">
    <Grid>
        <Label Content="Label"
               Name="myLabel" />
    </Grid>
</UserControl>

我需要:
1) 公开myLabelFontFamily 属性,因为它是MyUserControl 的属性。
2) *(真正的可选)定义 myLabel 内容为“MyUserControl1”、“MyUserControl2”等,就像添加多个控件时设计器所做的那样。

我应该如何公开该属性,例如序数属性(?)或依赖项(?)...

【问题讨论】:

    标签: .net wpf xaml wpf-controls


    【解决方案1】:

    将它们暴露为依赖属性,实际上控件上的每个属性都应该暴露为依赖属性。然后您可以使用绑定例如将属性附加到Label.FontFamily 属性:

    public void MyUserControl()
    {
        myLabel.SetBinding(Label.FontFamilyProperty, new Binding {
                                                              Path = "FontFamily",
                                                              Source = this,
                                                          });
    }
    

    这里FontFamily 中的Path setter 是您的属性的名称。

    P.S.:没有真正得到你的第二个问题。您能否改写一下或提供一些示例?

    【讨论】:

    • 第二个问题。假设您在设计器中放置了一个标签。名称,文本是“Label1”......现在,你放另一个,名称和文本将是“Label2”等。我需要我的 Label 的文本以相同的逻辑表现。
    【解决方案2】:

    FontFamily 在 Control 上声明,它是 UserControl 和 Label 的基础,并且是继承的 DependencyProperty。因此,除非您覆盖标签上的 FontFamily 值(本地值、样式、触发器等),否则您已经可以在 UserControl 上设置 FontFamily 并将其显示在标签上而无需执行任何其他操作。如果您需要在内部对其进行修改并将其推出以显示在 UserControl 上,您需要将 UserControl 的 FontFamily 绑定到具有 Mode=TwoWay 的标签。

    到第二部分 - 您需要设置一些计数机制,该机制在创建实例时递增,可能作为控件内的静态字段。然后,您可以递增该值并将其应用于 UserControl 构造函数中的 Label(这将取决于每个会话期间运行时的加载顺序和变量)。

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多