在 WPF 中创建可重用的用户控件
本文关键字:用户 控件 WPF 创建 | 更新日期: 2023-09-27 17:56:45
在我们使用 WPF for UI 构建的(相当大的)LOB 应用程序中,我们有很多包含相同类型的数据子对象的视图模型。例如,有很多地址
public class AddressViewModel : INotifyPropertyChanged
{
public string City {...}
public string ZipCode {...}
public string Address {...}
public string Number {...}
// INPC logic omitted
}
分散在业务对象中:
public class CustomerViewModel : INotifyPropertyChanged
{
public string Name {...}
public AddressViewModel BillingAddress {...}
public AddressViewModel DeliveryAddress {...}
/*
...
*/
}
是否可以构建一个可重用的自定义用户控件,我们可以将其绑定到任何地址子对象?
在旨在编辑客户详细信息的视图(可能是另一个自定义用户控件)中,我们希望放置这样的自定义控件
<UserControl x:Class="OurApp.View.AddressEditor"
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>
<TextBox x:Name="ZipCode" Text="{Binding Path=ZipCode, UpdateSourceTrigger = PropertyChanged}" Validation.ErrorTemplate="{x:Null}" HorizontalAlignment="Left" Height="23" Margin="10,19,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" />
<!-- other fields for the rest of AddressViewModel properties-->
</Grid>
</UserControl>
我们可以简单地在绑定到 CustomerViewModel 实例的视图中使用这样的视图
<TextBox x:Name="Name" Text="{Binding Path=Name, UpdateSourceTrigger = PropertyChanged}" Validation.ErrorTemplate="{x:Null}" />
<AddressEditor SomeProperty="{something that points to BillingAddress}" />
<AddressEditor SomeProperty="{something that points to DeliveryAddress}" />
正确的方法是什么?我们试图将绑定指向账单地址,但我们没有找到可行的方法......
提前感谢您的任何贡献,
是的,这应该很容易,要么使用 DataTemplate
创建一个外观控件,要么创建一个标准的 UserControl。诱使它将其DataContext
设置为完整的地址对象
<local:AddressControl DataContext="{Binding BillingAddress}"/>
这将允许你的新"地址控制"有这样的标记
<StackPanel Orientation="Vertical">
<Label Content="City"/>
<TextBox Content="{Binding City}"/>
<Label Content="ZipCode"/>
<TextBox Content="{Binding ZipCode}"/>
<Label Content="ZipCode"/>
<TextBox Content="{Binding ZipCode}"/>
<Label Content="Number"/>
<TextBox Content="{Binding Number}"/>
</StackPanel>
您可以将地址编辑器的数据上下文设置为 eg。 计费地址 只要计费地址具有用户控件中所需的属性,它就应该可以工作
<TextBox x:Name="Name" Text="{Binding Path=Name, UpdateSourceTrigger = PropertyChanged}" Validation.ErrorTemplate="{x:Null}" />
<AddressEditor DataContext="{Binding Path=BillingAddress}" />
除了设置数据上下文之外,还可以为用户控件创建一个依赖项属性,您可以在其中将计费地址绑定到该属性。