以下内容参考一个博客文章以及MSDN上的相应内容。
一、自定义属性
给一个控件添加自定义属性按如下方法即可:
public static readonly DependencyProperty RadiusXProperty =
DependencyProperty.Register("RadiusX", typeof(double), typeof(this), new UIPropertyMetadata(0.0));
public double RadiusX
{
get { return (double)GetValue(RadiusXProperty); }
set { SetValue(RadiusXProperty, value); }
}
这里,外部可以访问到的属性名字就是RadiusX,虽然它实际上是RadiusXProperty,Register函数需要的第二个参数是该属性的类型,第三个参数是父类的类型。
二、运用IMultiValueConverter进行多值绑定
假设我们有个window,有三个TextBox,其中第三个TextBox决定和被决定于前两个TextBox,相应代码如下:
<Window x:Class="BlogIMultiValueConverter.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BlogIMultiValueConverter"
Title="Window1" Height="237" Width="426">
<Grid>
<TextBox Height="23" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" />
<TextBox Margin="138,12,146,0" Name="textBox2" Height="23" VerticalAlignment="Top" />
<TextBox Height="21" Margin="12,77,12,0" Name="textBlock1" VerticalAlignment="Top" Background="LightCyan">
</TextBox>
</Grid>
</Window>
譬如box1的内容是abc,box2的内容是def, 我们希望block1的内容是abc def,而把block1的内容变成def abc的时候,则前两个box的内容就变成了def与abc。这时我们可以这样做。
首先定义一个IMultiValueConverter的衍生类
using System;
using System.Windows.Data;
namespace BlogIMultiValueConverter
{
public class NameMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return String.Format("{0} {1}", values[0], values[1]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
string[] splitv = ((string)value).Split(' ');
return splitv;
}
}
}
然后Window1的构造函数如下:
public Window1() {
InitializeComponent();
DataContext = new DataClass();
}
相应的.xaml文件改为
<Window x:Class="BlogIMultiValueConverter.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BlogIMultiValueConverter"
Title="Window1" Height="237" Width="426">
<Window.Resources>
<local:NameMultiValueConverter x:Key="NameMultiValueConverter" />
</Window.Resources>
<Grid>
<TextBox Height="23" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" Text="{Binding Path=FirstName,UpdateSourceTrigger=PropertyChanged}" />
<TextBox Margin="138,12,146,0" Name="textBox2" Height="23" VerticalAlignment="Top" Text="{Binding Path=Surname,UpdateSourceTrigger=PropertyChanged}" />
<TextBox Height="21" Margin="12,77,12,0" Name="textBlock1" VerticalAlignment="Top" Background="LightCyan">
<TextBox.Text>
<MultiBinding Converter="{StaticResource NameMultiValueConverter}">
<Binding Path="FirstName" />
<Binding Path="Surname" />
</MultiBinding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>
然后就可以了。