Declaratively sets the MyUserControl property to MyUserControl.xaml

Assuming we have this control:

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

    public string Foo { get; set; }
}

How can I set the value of the "Foo" property 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 the value for the property defined in the code.

+3
source share
5 answers

This can only be achieved in xaml by inheritance:

You provide an implementation for your control. Thus, the only way to achieve xaml value 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>
+1
source

, UserControl xaml . - :

<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>
+7

public MyUserControl{ this.Foo = "Hola";}

- :

<Window xmlns:mycontrol="Test"     ....

Intellisense xmlns

<mycontrol:MyUserControl       Foo="Hola"/>

, Foo, , DependencyProperty.

+1

, , UserControl. , Style, DependencyProperty. Binding.

Foo DependencyProperty, PropertyMetadata, DependencyProperty:

public static readonly DependencyProperty FooProperty = DependencyProperty.Register("Foo", typeof(String), typeof(MyUserControl), new PropertyMetadata("Hola"));

Otherwise, you are probably better off not setting a default value for the code.

0
source

How about a non string property. e.g. MyCustomObject =

0
source

Source: https://habr.com/ru/post/1704957/


All Articles