WPF隨手筆記
WPF 的資料繫結允許多個欄位與一個控制項繫結, 使用以下步驟說明:
- 撰寫一類別, 實作IMultiValueConverter介面, 處理多個欄位連接成一個值的作業
public class NameConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string name;
name = values[0] + " " + values[1];
return name;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
string[] splitValues = ((string)value).Split(' ');
return splitValues;
}
}
- 在Windows.Resource宣告這個類別為資源
<Window.Resources>
<c:NameConverter x:Key="NameConverter"/>
<ObjectDataProvider x:Key="NorthwindDataSetDS" ObjectType="{x:Type WpfDataBinding:NorthwindDataSet}" d:IsDataSource="True"/>
</Window.Resources>
<Window.DataContext>
<Binding Path="Employees" Mode="Default" Source="{StaticResource NorthwindDataSetDS}"/>
</Window.DataContext>
- 在控制項要繫結的屬性上使用MultiBinding設定Converter及繫結的欄位
<TextBox Margin="32,80,69.6,0" VerticalAlignment="Top" Height="48" TextWrapping="Wrap">
<TextBox.Text>
<MultiBinding Converter="{StaticResource NameConverter}"
ConverterParameter="FormatLastFirst">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBox.Text>
</TextBox>
繫結Northwind的Employees Table, 執行結果:
沒有留言:
張貼留言