TextBlock綁定屬性
綁定單個屬性及轉換器
<UserControl.Resources>
<cvt:StateConv x:Key="stateConv"/>
</UserControl.Resources>
...
<TextBlock Text="{Binding Name, StringFormat={}{0:F2}, Converter="{StaticResource stateConv}"}"/>
using System;
using System.Globalization;
using System.Windows.Data;
public class StateConv: IValueConverter
{
// 此文本將顯示在控件中(比如:TextBox)
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int type = 0;
string rslt = string.Empty;
if (int.TryParse(value.ToString(), out type))
{
if (type == 1) { rslt = "正常"; }
else { rslt = "異常"; }
}
return rslt;
}
// 目標數據格式轉換為原數據格式(正常->1)
// 當您更改控件TextBox的值時,ConvertBack方法將在綁定再次觸發時調用(默認OnFocusLost)
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (string.IsNullOrEmpty(value?.ToString()))
return -1;
var item = TypeResource.FirstOrDefault(x => x.DisplayText == value.ToString());
if (item == null)
{
return -1;
}
return item.Key;
}
}
轉換器2
數值轉換,顯示指定枚舉類型的文本描述
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && int.TryParse(value.ToString(), out int type))
{
if (Enum.IsDefined(typeof(PropertyNameEnumType), type))
{
var @enum = (PropertyNameEnumType)type;
return @enum.GetEnumDescription();
}
}
return "未知狀態";
}
多重綁定1
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}({1})">
<Binding Path="Name1" TargetNullValue="用默認值來顯示為空的字段" />
<Binding Path="Name2" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
StringFormat要求它的目標是string類型。 可在指定控件內嵌套TextBlock進行自定義格式轉換。
若要體現動態數據,屬性所屬類需要實現INotificationPropertyChanged接口,綁定的屬性可以響應屬性更改事件。
多重綁定2
<UserControl.Resources>
<cvt:MultiStateConv x:Key="multiStateConverter"/>
<cvt:MultiVersionTypeConv x:Key="multiVersionTypeConverter"/>
</UserControl.Resources>
...
<TextBlock>
<TextBlock.Content>
<MultiBinding Converter="{StaticResource multiStateConverter}">
<Binding Path="Name"/>
<Binding Path="Name2"/>
</MultiBinding>
</TextBlock.Content>
</TextBlock>
<DataGridTextColumn Header="版本類型" Width="*">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource multiVersionTypeConverter}" ConverterParameter="{StaticResource multiStateConverter}">
<Binding Path="Type1"/>
<Binding Path="Type2"/>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
using System;
using System.Globalization;
using System.Windows.Data;
[ValueConversion(typeof(object[]), typeof(string))]
class MultiStateConv : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var cvt = parameter as MultiStateConv;
string rslt = string.Empty;
if (int.TryParse(values[0].ToString(), out int type))
{
//...
}
if (int.TryParse(values[1].ToString(), out int type2))
{
//...
}
return rslt;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
可直接調用資源詞典
Converter.xaml
{Binding Converter={StaticResource Boolean2VisibilityConverter}}
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="clr-namespace:XXX.Converters">
<BooleanToVisibilityConverter x:Key="Boolean2VisibilityConverter"/>
......
</ResourceDictionary>
DataGrid中,編輯狀態下觸發事件
<DataGridTextColumn Width="auto" IsReadOnly="False" MinWidth="110" Binding="{Binding Name}" Header="名稱">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<EventSetter Event="TextChanged" Handler="DataGridTextColumn_Name_TextChanged"/>
<EventSetter Event="LostFocus" Handler="DataGridTextColumn_Name_LostFocus"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
RadioButton綁定屬性
<UserControl.Resources>
<cvt:RadioCheckConv x:Key="radioCheckConverter"/>
</UserControl.Resources>
<RadioButton Content="XXX" HorizontalAlignment="Center" GroupName="GroupName1"
IsChecked="{Binding PropertyName1, Converter={StaticResource radioCheckConverter}, ConverterParameter=1}"/>
其中,屬性PropertyName1是可通知的;
using System;
using System.Windows.Data;
public class RadioCheckConv : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || parameter == null)
{
return false;
}
if (value.ToString().Equals(parameter.ToString()))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || parameter == null)
{
return null;
}
if ((bool)value)
{
return parameter.ToString();
}
return null;
}
}
TextBox綁定屬性
<TextBox x:name="txt" Text="{Binding PropertName, Mode=TwoWay, UpdateSourceTrigger=Default}" />
控件綁定屬性時,UpdateSourceTrigger默認為Default。源PropertName不會隨着Text屬性的改變而立即更新;TextBox中的變化並不是立即傳遞到源,而是在TextBox失去焦點后,源才更新。
UpdateSourceTrigger枚舉 | 說明 | 備注 |
---|---|---|
Default | 默認值 | 默認為LostFocuse |
Explicit | 當應用程序調用 UpdateSource 方法時生效 | 通過代碼手動推送來更新 |
LostFocus | 失去焦點的時候觸發 | |
PropertyChanged | 屬性改變的時候觸發 | 源會立即更新 |
using System.Windows.Data;
private void btnUpdateSource_Click(object sender, RoutedEventArgs e)
{
// Explicit時,手動更新綁定的屬性
BindingExpression binding = txt.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
后台綁定
<cvt:IntToBoolConv x:Key="intToBoolConverter"/>
<CheckBox Content="啟用" x:Name="CheckBox1"
IsChecked="{Binding IsEnable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource intToBoolConverter}}" />
this.DataContext = this; // Prism可省略此步;此時IsEnable可通知客戶端即可,不要求是依賴屬性propdp
相當於后台實現
<CheckBox Content="啟用" x:Name="CheckBox1" />
using System.Windows.Data;
BindingOperations.SetBinding(CheckBox1, // 控件名稱
CheckBox.IsCheckedProperty, // 控件屬性
new Binding // 綁定內容
{
Path = new PropertyPath("IsEnable"), // 依賴屬性 IsEnable
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
Converter = new IntToBoolConv(),
Source = this, // 屬性所屬對象
});