WPF 绑定回退值设置为绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1915562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Binding FallbackValue set to Binding
提问by HaxElit
Is there a way to have another binding as a fallback value?
有没有办法将另一个绑定作为后备值?
I'm trying to do something like this:
我正在尝试做这样的事情:
<Label Content="{Binding SelectedItem.Name, ElementName=groupTreeView,
FallbackValue={Binding RootGroup.Name}}" />
If anyone's got another trick to pull it off, that would be great.
如果有人有其他技巧来实现它,那就太好了。
回答by kiwipom
What you are looking for is something called PriorityBinding (#6 on thislist)
您正在寻找的是称为 PriorityBinding 的东西(此列表中的#6 )
(from the article)
(来自文章)
The point to PriorityBinding is to name multiple data bindings in order of most desirable to least desirable. This way if the first binding fails, is empty and/or default, another binding can take it's place.
PriorityBinding 的要点是按最理想到最不理想的顺序命名多个数据绑定。这样,如果第一个绑定失败、为空和/或默认,另一个绑定可以取而代之。
e.g.
例如
<TextBox>
<TextBox.Text>
<PriorityBinding>
<Binding Path="LastNameNonExistant" IsAsync="True" />
<Binding Path="FirstName" IsAsync="True" />
</PriorityBinding>
</TextBox.Text>
</TextBox>
回答by Sven
If you run into problems with binding to null values and PriorityBinding (as Shimmy pointed out) you could go with MultiBinding and a MultiValueConverter like that:
如果您遇到绑定到空值和 PriorityBinding 的问题(正如 Shimmy 指出的),您可以使用 MultiBinding 和 MultiValueConverter 这样的:
public class PriorityMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.FirstOrDefault(o => o != null);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Usage:
用法:
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource PriorityMultiValueConverter}">
<Binding Path="LastNameNull" />
<Binding Path="FirstName" />
</MultiBinding>
</TextBox.Text>
</TextBox>
回答by James Hay
Under what conditions would you like it to use the Fallback value? How would you determine that a binding has failed? A binding is still valid even if it's bound to a null value.
您希望它在什么条件下使用 Fallback 值?您如何确定绑定失败?即使绑定到空值,绑定仍然有效。
I think a good bet may be to use a converter to convert to a default value if the binding returns null. I'm not sure how you could default to another bound value though.
如果绑定返回 null,我认为一个好的选择可能是使用转换器转换为默认值。不过,我不确定您如何默认为另一个绑定值。
Check out converters here