Toj*_*oji 4 c# data-binding wpf
我觉得我缺少一个相当基本的概念,WPF,当涉及到数据绑定,但我似乎无法找到谷歌的关键字的正确组合,以找到我后,所以或许SO社区可以提供帮助.:)
我有一个WPF用户控件需要数据绑定到两个单独的对象才能正确显示.必须从外部源动态设置两个对象.到目前为止,我只是一直在使用的形式动态对象绑定的DataContext属性,但只允许被引用的一个对象.我觉得这是一个简单的问题,我必须遗漏一些明显的东西.
我以前的尝试看起来像这样:
<UserControl.Resources>
<src:Person x:Key="personSource" />
<src:Job x:Key="jobSource" />
</UserControl.Resources>
<TextBox Text="{Binding Source={StaticResource personSource}, Path=Name" />
<TextBox Text="{Binding Source={StaticResource jobSource}, Path=Address" />
Run Code Online (Sandbox Code Playgroud)
这将绑定到任何默认我给班就好了,但如果我尝试动态地设置在代码中的对象(如我在下面)我没有看到任何改变.
Person personSource = FindResource("personSource") as Person;
personSource = externalPerson;
Job jobSource= FindResource("jobSource") as Job;
jobSource = externalJob;
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
我可能会使用带有两个DependencyProperties的CustomControl.然后,使用自定义控件的外部站点可以将他们想要的数据绑定到该控件,也可以使用自定义控件来模板控件在不同情况下的显示方式.
自定义控件代码如下所示:
public class CustomControl : Control
{
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("Person", typeof(Person), typeof(CustomControl), new UIPropertyMetadata(null));
public Person Person
{
get { return (Person) GetValue(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
public static readonly DependencyProperty JobProperty =
DependencyProperty.Register("Job", typeof(Job), typeof(CustomControl), new UIPropertyMetadata(null));
public Job Job
{
get { return (Job) GetValue(JobProperty); }
set { SetValue(JobProperty, value); }
}
static CustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
}
}
Run Code Online (Sandbox Code Playgroud)
Generic.xaml是一个应该为您创建的文件,并且可以具有如下所示的Style:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3">
<Style TargetType="{x:Type local:CustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel>
<TextBox Text="{TemplateBinding Person.Name}" />
<TextBox Text="{TemplateBinding Job.Address}" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
最后,当你去使用你的控件时,你会做这样的事情.
<src:CustomControl Person="{Binding Person}" Job="{Binding Job}" />
Run Code Online (Sandbox Code Playgroud)