![](/img/trans.png)
[英]DataTemplate Based on Value of Bound Property in ItemsSource of TabControl
[英]Change element property based on bound value
我需要根據綁定對象中的值更改Image元素的屬性。
我有一個圖像元素:
<Image Source="{Binding Thing.Url}" Stretch="UniformToFill" HorizontalAlignment="Left"/>
如果Thing.OtherProperty = true
,那么我想將HorizontalAlignment="Center"
添加到Image元素。
注意,Image元素位於DataTemplate中,用於應用程序中的各個位置。
實現這一目標的最佳方法是什么?
這是您使用綁定轉換器的地方
在您的情況下,您想要基於布爾值更改HorizontalAlignment
屬性。 您首先需要編寫一個實現IValueConverter
的類,您將在其中編寫轉換邏輯:
public class AlignmentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if ((bool)value)
return Windows.UI.Xaml.HorizontalAlignment.Center;
return Windows.UI.Xaml.HorizontalAlignment.Left;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
*如果您將此綁定到非布爾值的屬性,您可能需要更好地處理錯誤
要使用此功能,您需要在頁面頂部導入您的coverters命名空間
xmlns:converters="using:*yournamespace*"
...將轉換器聲明為資源:
<converters:AlignmentConverter x:Key="HorizontalAlignmentConverter"/>
...並將其用作綁定中的參數
<Image Source="{Binding Thing.Url}" Stretch="UniformToFill" HorizontalAlignment="{Binding Thing.OtherProperty, Converter={StaticResource HorizontalAlignmentConverter}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.