假设我们有这样的控制:
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中为代码隐藏中定义的属性设置值。
答案 0 :(得分: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>
答案 1 :(得分:1)
在你的控件中,在构造函数中设置它
public MyUserControl{ this.Foo = "Hola";}
如果您在其他地方使用控件:
<Window xmlns:mycontrol="Test" ....
Intellisense将使用正确的xmlns语法
为您提供帮助<mycontrol:MyUserControl Foo="Hola"/>
我不确定,但Foo可能需要成为DependencyProperty。
答案 2 :(得分:1)
这只能通过继承在xaml中实现:
您正在为您的控件提供实现。因此,在xaml中为控件实现值的唯一方法是通过继承。
您的第二个UserControl将如下所示:
<Test:MyUserControl x:Class="Test.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:Test="clr-namespace:Test"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Test:MyUserControl.Foo>Hola</Test:MyUserControl.Foo>
</Test:MyUserControl>
或:
<Test:MyUserControl x:Class="Test.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:Test="clr-namespace:Test"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Foo="Hola">
</Test:MyUserControl>
答案 3 :(得分:0)
您真正想要的是UserControl
上属性的默认值。很遗憾,除非是Style
,否则您无法在DependencyProperty
中进行设置。它也不能成为Binding
的目标。
如果Foo
是DependencyProperty
,您可以在宣布DependencyProperty
后在PropertyMetadata
中进行设置:
public static readonly DependencyProperty FooProperty = DependencyProperty.Register("Foo", typeof(String), typeof(MyUserControl), new PropertyMetadata("Hola"));
否则你最好在代码隐藏中设置默认值。
答案 4 :(得分:0)
非字符串属性怎么样?例如MyCustomObject =