Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaratively set property of MyUserControl in MyUserControl.xaml

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.

like image 386
alex2k8 Avatar asked Dec 06 '25 05:12

alex2k8


1 Answers

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>
like image 129
Andrew Jackson Avatar answered Dec 07 '25 22:12

Andrew Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!