大多数转换器不带参数或一个固定参数,并且很容易绑定到:
<local:MyConverter x:Key="MyConverterInstance" />
<TextBox Text="{Binding Path=MyTime,
Converter={StaticResource MyConverterInstance},
ConverterParameter='yyyy/MM/dd'}" />
但是,如果我希望该格式成为用户可以更改的动态属性,我不能做这样的事情,对吧?:
<TextBox Text="{Binding Path=MyTime,
Converter={StaticResource MyConverterInstance},
ConverterParameter={Binding Path=UserFormat}}" />
所以我唯一的选择是在MyConverter上定义DependencyProperty以进行绑定。但我的转换器定义是StaticResource。我不能去
<local:MyConverter x:Key="MyConverterInstance"
Format="{Binding Path=UserFormat}"/>
因为StaticResources上没有DataContext。我该怎么设置呢?
答案 0 :(得分:5)
您无法绑定到转换器参数,但您可以使用Multibinding。 例如:http://www.switchonthecode.com/tutorials/wpf-tutorial-using-multibindings 或How to simply bind this to ConverterParameter?
(阿兰)所以只是将这个链接的答案翻译成符合这个问题的答案:
<TextBlock>
<TextBlock.Resources>
<local:MyConverter x:Key="MyConverterInstance" />
</TextBlock.Resources>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="MyTime" />
<Binding Path="UserFormat" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
DateTime time = (DateTime)values[0];
string format = values[1].ToString();
return time.ToString(format);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}