[英]How to use multibinding in Button width
我正在嘗試將Multibinding與XAML中具有Button控件和Width屬性的轉換器結合使用,但無法正常工作。
轉換器是:
public class ColumnsToWidthConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return 40;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
為了測試目的,它已經硬編碼了40個。
XAML定義為:
<Button
Height="{Binding ElementName=root,Path=KeyHeight}"
FontSize="{Binding FontSize}"
Content="{Binding Display}"
Command="{Binding ElementName=root, Path=Command}"
CommandParameter="{Binding}"
Style="{StaticResource SelectedButton}">
<Button.Width>
<MultiBinding Converter="{StaticResource ColumnsToWidthConverter}">
<Binding Path="Columns"/>
<Binding Path="KeyHeight" ElementName="root"/>
</MultiBinding>
</Button.Width>
</Button>
該按鈕從ListView
呈現,並在ListView.ItemTemplate
定義。 在調試應用程序時,將傳遞轉換器並返回40的值。 object[] values
參數包含在MultiBinding路徑中傳遞的正確值。 但是,按鈕的寬度設置為其內容,而不是如上例所示的40。
ColumnsToWidthConverter
在父ListView.Resources
定義。
<converter:ColumnsToWidthConverter x:Key="ColumnsToWidthConverter"/>
當我刪除MultiBinding並將XAML定義中的Width屬性設置為40時,按鈕將正確呈現。
root
元素是usercontrol本身,而KeyHeight
是DependencyProperty
。
如何使用多重綁定設置按鈕寬度?
問題不在於多重綁定,而在於轉換器本身。 在實現轉換器時,期望您返回與控件期望值相同的類型(因為您是在實現轉換器,所以沒有隱式轉換)。 在這種情況下, Width
屬性是double
,因此您應該返回相同類型的值:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return 40d;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.