在MyUserControl.xaml中声明性地设置MyUserControl的属性

ale*_*2k8 3 wpf xaml user-controls

假设我们有这样的控制:

public partial class MyUserControl : UserControl
{
    public MyUserControl() {
        InitializeComponent();
    }

    public string Foo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何在MyUserControl.xaml中以声明方式设置"Foo"属性值?

<UserControl x:Class="Test.MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!-- Looking for some thing like this -->
    <Foo>Hola</Foo>

</UserControl>
Run Code Online (Sandbox Code Playgroud)

更清楚:如何在XAML中为代码隐藏中定义的属性设置值.

And*_*son 7

我在过去发现,您可以使用样式在xaml上设置UserControl的属性而不继承.尝试这样的事情:

<UserControl x:Class="Test.MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c="clr-namespace:Test.MyUserControl" >

    <UserControl.Style>
        <Style>
            <Setter Property="c:MyUserControl.Foo" Value="Hola" />
        </Style>
    </UserControl.Style>

</UserControl>
Run Code Online (Sandbox Code Playgroud)