Reputation: 43214
Assuming we have such control:
public partial class MyUserControl : UserControl
{
public MyUserControl() {
InitializeComponent();
}
public string Foo { get; set; }
}
How can I set "Foo" property value declaratively in MyUserControl.xaml?
<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>
To be more clear: How can I set in XAML a value for the property defined in code-behind.
Upvotes: 3
Views: 3186
Reputation: 774
I've found in the past that you can use a style to set properties on a UserControl from xaml without inheritance. Try something like this:
<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>
Upvotes: 7
Reputation: 27055
This can only be achieved in xaml by inheritance:
You are providing an implementation for your control. So the only way to achieve a value in xaml for your control is through inheritance.
Your second UserControl will look like this:
<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>
or:
<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>
Upvotes: 1
Reputation: 11820
It seems like what you really want is a default value for properties on your UserControl
. Unfortunately you can't set it in a Style
unless it's a DependencyProperty
. It also can't be the target of a Binding
.
If Foo
were a DependencyProperty
, you could set it in the PropertyMetadata
when you declare your DependencyProperty
:
public static readonly DependencyProperty FooProperty = DependencyProperty.Register("Foo", typeof(String), typeof(MyUserControl), new PropertyMetadata("Hola"));
Otherwise you're probably better off setting the default value in code-behind.
Upvotes: 0
Reputation: 1536
In your control set it in the constructor
public MyUserControl{ this.Foo = "Hola";}
If you're using the control somewhere else:
<Window xmlns:mycontrol="Test" ....
Intellisense will help you here with proper syntax of xmlns
<mycontrol:MyUserControl Foo="Hola"/>
I'm not sure, but Foo may probably need to be a DependencyProperty.
Upvotes: 1