我有以下 XAML 代碼:
<TextBox Text="Image.Bytes" IsReadOnly="True"/>
<TextBox IsReadOnly="True">
<TextBox.Text>
<MultiBinding Converter="{StaticResource ConcatTextConverter}" ConverterParameter="x">
<Binding Path="Image.Width"/>
<Binding Path="Image.Height"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
ConcatTextConverter 是一個簡單的轉換器,如下所示:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string result = string.Empty;
string separator = parameter?.ToString() ?? "";
if(values?.Any() == true)
{
result = string.Join(separator, values);
}
return result;
}
當屬性“Image”為空時,就會出現問題。第一個文本框只顯示任何內容。
但是,第二個顯示“DependencyProperty.UnsetValue}x{DependencyProperty.UnsetValue}”
給轉換器的值的型別是:values[0].GetType() {Name = "NamedObject" FullName = "MS.Internal.NamedObject"} System.Type {System.RuntimeType} 不幸的是我無法訪問這個鍵入 MS.Internal.NamedObject 以在轉換器中對其進行過濾以防萬一。
現在的問題是:當系結鏈中的某個物件為空時,首先防止呼叫轉換器的最佳方法是什么?- 或者其次:在轉換器中識別此類“值”的最佳方法是什么?
uj5u.com熱心網友回復:
您無法避免呼叫轉換器,但您可以檢查是否所有系結都產生了值。
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
string result = string.Empty;
string separator = parameter?.ToString() ?? "";
if (values.All(value => value != DependencyProperty.UnsetValue))
{
result = string.Join(separator, values);
}
return result;
}
uj5u.com熱心網友回復:
您不需要轉換器來連接字串。您所需要的只是StringFormatMultiBinding 上的一個屬性。
此外,您不需要TextBox. 由于您已將其設定為IsReadOnly="true",因此 aTextBlock會做同樣的事情
當沒有影像時,此系結將為您提供一個空字串
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}x{1}">
<Binding Path="Image.Width"/>
<Binding Path="Image.Height"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
如果您希望在沒有影像時使用像“0x0”這樣的字串,則可以在各個系結上使用“FallbackValue”屬性來實作這一點。
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}x{1}">
<Binding Path="Image.Width" FallbackValue="0"/>
<Binding Path="Image.Height" FallbackValue="0"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
編輯添加:該FallbackValue方法也適用于 Clemens 出色的答案。無論您使用哪種方法,他提出的讓您的轉換器更強大的建議都是一件好事。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/478595.html
下一篇:圓內的整數點-遞回問題
