繁体   English   中英

如何使自定义XAML用户控件可绑定?

[英]How do you make a custom XAML User Control bindable?

我正在制作一个简单的演示来学习如何创建一个可绑定的用户控件。 我创建了一个简单的类:

class Person
{
    public string firstName;
    public string lastName;    
    public Person(string first, string last)
    {
        firstName = first;
        lastName = last;
    }
}

而且一个非常简单的用户控件:

<UserControl x:Class="Example.ExampleHRControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock x:Name="textFirstName"></TextBlock>
        <TextBlock x:Name="textLastName"></TextBlock>
    </Grid>
</UserControl>

我想知道的是,为了能够像普通控件一样在上下文中使用用户控件,我需要做什么。 我可以将它添加到MainWindow

<local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl>

然后我可以通过后面的代码解决它并添加值:

Hr1.textFirstName.Text = "John";
Hr1.textLasttName.Text = "Doe";

我希望能够创建Person类的实例,并简单地将主窗口上的控件绑定到Person类。

要完成这项工作,您需要做几件事。

在您的代码隐藏中,为您希望控件了解的Person对象添加依赖项属性:

   public static readonly DependencyProperty PersonProperty =
                          DependencyProperty.Register("Person", typeof(Person),
                                                      typeof(ExampleHRControl));

   public Person Person
   {
      get { return (Person)GetValue(PersonProperty); }
      set { SetValue(PersonProperty, value); }
   }

在XAML中,将代码隐藏设置为数据上下文,并将绑定添加到person对象:

<UserControl x:Class="Example.ExampleHRControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300"
         x:Name="This">
    <Grid>
        <TextBlock x:Name="{Binding Path=Person.FirstName, ElementName=This}"/>
        <TextBlock x:Name="{Binding Path=Person.LastName, ElementName=This}"/>
    </Grid>
</UserControl>

现在,每当设置Person属性时,您的控件将使用与Person关联的First和Last名称更新自身。

你想要什么叫做Dependancy Property你可以从xaml绑定到它。
1 - 创造领域

public static readonly DependencyProperty FirstNameProperty = 
    DependencyProperty.Register(
    "FirstName", typeof(Strin),

2 - 创建属性

public String FirstName
{
    get { return (String)GetValue(FirstNameProperty); }
    set { SetValue(FirstNameProperty, value); }
}

3-您可以在XAML中使用它来绑定它或只是使用它

<local:YourControlName FirstName="john"/>

<local:YourControlName FirstName="{Binding MyFirstName}"/>
  • 使用Resharper将帮助您制作干净的代码并拥有非常强大的IntelliSense

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM