将XAML属性值设置为用户控件

8
我在WPF中有一个用户控件,我希望其中一个标签的文本可以从使用它的XAML文件中读取。因此...
我的用户控件:
 <UserControl x:Class="muc">
        <Label Foreground="#FF7800" FontSize="20" FontWeight="Bold">          
             <Label.Content>
                <Binding ElementName="TestName" Path="." />
             </Label.Content>
        </Label>
 </UserControl>

然后使用它:
 <mycontorls:muc TestName="This is a test" />

但它不起作用... 我该如何读取这些属性?

1
你所需要的是在 UserControl 的代码后台中创建一个名为 TestName 的依赖属性,就像 AlvinfromDiaspar 所描述的那样。然后,你可以使用 ElementName(Quartermeister 的回答)或 RelativeSource 绑定(Pavel Minaev 的回答)将 Label 的内容绑定到 UserControl 的 TestName 属性。 - Amsakanna
4个回答

8
我尝试了前两个答案,代码可以工作,但在XAML上不起作用(当使用控件时也无法在设计视图中查看更改)。
为使属性像任何其他本机属性一样工作,需要完成以下全部过程: (示例添加了一个可为空的依赖属性,以文本或默认值的形式显示在控件中)
  1. In the code file:

    1.a Define a dependency property:

    public static readonly DependencyProperty MyNumberProperty = DependencyProperty.Register("MyNumber", typeof(Nullable<int>), typeof(MyUserControl), new PropertyMetadata(null, new PropertyChangedCallback(OnMyNumberChanged)));
    

    1.b Implement the OnMyNumberChanged Callback:

    private static void OnMyNumberChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args){
        // When the color changes, set the icon color PlayButton
        MyUserControl muc = (MyUserControl)obj;
        Nullable<int> value = (Nullable<int>)args.NewValue;
        if (value != null)
        {
            muc.MyNumberTextBlock.Text = value.ToString();
        }
        else
        {
            muc.MyNumberTextBlock.Text = "N/A";
        }
    }
    

    1.c implement the MyNumber property (not dependency) to use the dependency property for easy in code use:

    public Nullable<int> MyNumber{
        get
        {
            return (Nullable<int>)GetValue(MyNumberProperty);
        }
        set
        {
            SetValue(MyNumberProperty, value);
            OnTargetPowerChanged(this, new DependencyPropertyChangedEventArgs(TargetPowerProperty, value, value));    // Old value irrelevant.
        }
    }
    
  2. In the XAML file bind the TextBlock control's text to the property (not dependency) to get the default value of the dependency property in case it is not set by the user of the control (assuming you called your root element of the user control "RootElement"):

这段代码:
 < TextBlock Name="MyNumberTextBlock" Text="{Binding MyNumber, ElementName=RootElement}"/>

5
如果您给根UserControl元素命名,那么您可以使用ElementName引用它:
<UserControl x:Class="muc"
             Name="rootElement">
    <Label Foreground="#FF7800" FontSize="20" FontWeight="Bold">
        <Label.Content>
            <Binding ElementName="rootElement" Path="TestName" />
        </Label.Content>
    </Label>
</UserControl>

你可以使用标记扩展语法来使它更短:
<UserControl x:Class="muc"
             Name="rootElement">
    <Label Foreground="#FF7800" FontSize="20" FontWeight="Bold"
           Content="{Binding TestName, ElementName=rootElement}"/>
</UserControl>

请记住,在设置属性之前,您的控件将被创建。您需要实现INotifyPropertyChanged或者使TestName成为依赖属性,以便在属性设置完成后重新评估绑定。


4

我只在Silverlight中做过这个,但如果它以完全相同的方式运行,我不会感到惊讶!

// <summary>
// Xaml exposed TextExposedInXaml property.
// </summary>
public static readonly DependencyProperty TestNameProperty = DependencyProperty.Register("TestName", typeof(string), typeof(NameOfMyUserControl), new PropertyMetadata(string.empty));

// <summary>
 // Gets or sets the control's text
// </summary>
public string TextExposedInXaml
{
            get
            {
                return (string)GetValue(TestNameProperty );
            }

            set
            {
                SetValue(TestNameProperty , value);

                // set the value of the control's text here...!
            }
}

0

{Binding ElementName=x} 绑定到元素树中名称为 x元素,这里没有涉及到属性 TestName。如果您想在用户控件上定义属性,则必须在对应于该用户控件的类中定义该属性(在您的情况下是 muc),并使用 {Binding RelativeSource={RelativeSource FindAncestor, ...}} 引用它在您的用户控件上(有关详细信息,请参见 此处),或者给它一个名称,以便您可以使用 ElementName


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接