wpf - 在 MyUserControl.xaml 中以声明方式设置 MyUserControl 的属性

标签 wpf xaml user-controls

假设我们有这样的控制:

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

    public string Foo { get; set; }
}

如何在 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>

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

最佳答案

我过去发现,您可以使用样式从 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>

关于wpf - 在 MyUserControl.xaml 中以声明方式设置 MyUserControl 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/658045/

相关文章:

c# - 如何在 WPF 窗口中只允许统一调整大小?

c# - 用户控件中具有 CompositeCollection 的 WPF ComboBox 不起作用 : SelectedIndex set to -1

c# - 有没有办法在毛伊岛放置一个按钮来打开弹出窗口

c# - 如何获取自定义用户控件内的所有文本框?

c# - 用户控件不呈现 ascx 的内容

WPF : How to move a maximized custom window?

c# - 如何将矩形的边距绑定(bind)到顶部/底部和左/右的两个 slider

ASP.NET 用户控件 OnError

c# - WPF 应用程序的内容调整大小事件

silverlight - Windows Phone 中的 XAML 字符串格式