我给你一个名为AddressControl 的UserControl 类,它可以在不依赖外部对象的情况下被重用。以及从外部控制到内部控制的任何变化。
AddressControl.cs
public partial class AddressControl : UserControl, IDataErrorInfo
{
public string City
{
get { return (string)GetValue(CityProperty); }
set { SetValue(CityProperty, value); }
}
// Using a DependencyProperty as the backing store for City. This enables styling, binding, etc...
public static readonly DependencyProperty CityProperty =
DependencyProperty.Register("City", typeof(string), typeof(AddressControl), new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnCityChanged)));
private static void OnCityChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
AddressControl ac = new AddressControl();
ac.ChangeCityText();
}
public void ChangeCityText()
{
txtCity.Text = City;
}
public string Street
{
get { return (string)GetValue(StreetProperty); }
set { SetValue(StreetProperty, value); }
}
// Using a DependencyProperty as the backing store for Street. This enables styling, binding, etc...
public static readonly DependencyProperty StreetProperty =
DependencyProperty.Register("Street", typeof(string), typeof(AddressControl), new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnStreetChanged)));
private static void OnStreetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
AddressControl ac = new AddressControl();
ac.ChangeStreetText();
}
public void ChangeStreetText()
{
txtStreet.Text = Street;
}
public AddressControl()
{
InitializeComponent();
DataContext = this;
}
public string Error
{
get
{
return null;
}
}
public string this[string name]
{
get
{
string result = null;
if (name == "City")
{
if (string.IsNullOrEmpty(City) || string.IsNullOrWhiteSpace(City))
{
result = "please enter city";
}
}
if (name == "Street")
{
if (string.IsNullOrEmpty(Street) && string.IsNullOrWhiteSpace(Street))
{
result = "please enter street";
}
}
return result;
}
}
}
AddressControl.xaml
<UserControl x:Class="WpfApp1.AddressControl"
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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d" Width="600">
<UserControl.Resources>
<Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
<Setter Property="FontWeight" Value="Normal"></Setter>
<Setter Property="FontSize" Value="14"></Setter>
<Setter Property="Margin" Value="0"></Setter>
<Setter Property="FontFamily" Value="Arial"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border KeyboardNavigation.IsTabStop="False" x:Name="bg" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="2">
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Opacity" TargetName="bg" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="bg" Value="#FF7EB4EA"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" TargetName="bg" Value="#FF7EB4EA"/>
</Trigger>
<Trigger Property="Validation.HasError" Value="True">
<Trigger.Setters>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="BorderThickness" TargetName="bg" Value="2"/>
<Setter Property="BorderBrush" TargetName="bg" Value="Red"/>
</Trigger.Setters>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid FlowDirection="LeftToRight" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition MinWidth="460"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="City :" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Margin="5 0 0 0"></TextBlock>
<TextBox Style="{StaticResource CustomTextBoxTextStyle}" TabIndex="1" Grid.Row="0" Grid.Column="1" x:Name="txtCity" Padding="10 10 10 3" BorderThickness="2" MinWidth="260" Height="38" HorizontalAlignment="Left" VerticalAlignment="Center">
<TextBox.Text>
<Binding Path="City"
ValidatesOnExceptions="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<DockPanel>
<TextBlock FontSize="11" FontStyle="Italic" Foreground="Red" Margin="10 10 0 0" DockPanel.Dock="Right"
Text="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
<AdornedElementPlaceholder x:Name="ErrorAdorner"
></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
<TextBlock Text="Street :" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" Margin="5 0 0 0"></TextBlock>
<TextBox Style="{StaticResource CustomTextBoxTextStyle}" TabIndex="2" Grid.Row="1" Grid.Column="1" x:Name="txtStreet" Padding="10 10 10 3" BorderThickness="2" MinWidth="260" Height="38" HorizontalAlignment="Left" VerticalAlignment="Center">
<TextBox.Text>
<Binding Path="Street"
ValidatesOnExceptions="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<DockPanel>
<TextBlock FontSize="11" FontStyle="Italic" Foreground="Red" Margin="10 10 0 0" DockPanel.Dock="Right"
Text="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
<AdornedElementPlaceholder x:Name="ErrorAdorner" KeyboardNavigation.IsTabStop="False"
></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
</Grid>
</UserControl>
现在使用:您可以立即绑定或更改债务金额
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel VerticalAlignment="Center">
<local:AddressControl x:Name="addressControl" City="Paris" Street="Street Menia"></local:AddressControl>
<Button x:Name="btnTest" Content="Test" Width="100" Click="btnTest_Click" Margin="0 10 0 0"></Button>
</StackPanel>
</Window>
下面这行可以替换
<local:AddressControl x:Name="addressControl" City="Paris" Street="Street Menia"></local:AddressControl>
ٌ有了这个代码
<local:AddressControl x:Name="addressControl" City="{Binding ShippingCity}" Street="{Binding ShippingStreet}"></local:AddressControl>
主窗口中的按钮点击事件
private void btnTest_Click(object sender, RoutedEventArgs e)
{
string result = "";
if (Validation.GetHasError(addressControl.txtCity))
{
result = Validation.GetErrors(addressControl.txtCity).FirstOrDefault().ErrorContent.ToString();
}
MessageBox.Show(result);
}