Cad*_*ris 9 c# data-binding wpf ivalueconverter
我需要根据要绑定的对象中标识的单元系统确定运行时StringFormat
的某些TextBlocks
绑定.
我有一个具有依赖属性的转换器,我想绑定.Bound值用于确定转换过程.
public class UnitConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty IsMetricProperty =
DependencyProperty.Register("IsMetric", typeof(bool), typeof(UnitConverter), new PropertyMetadata(true, ValueChanged));
private static void ValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
((UnitConverter)source).IsMetric = (bool)e.NewValue;
}
public bool IsMetric
{
get { return (bool)this.GetValue(IsMetricProperty); }
set { this.SetValue(IsMetricProperty, value); }
}
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (IsMetric)
return string.Format("{0:0.0}", value);
else
return string.Format("{0:0.000}", value);
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
我宣布转换器
<my:UnitConverter x:Key="Units" IsMetric="{Binding Path=IsMetric}"/>
Run Code Online (Sandbox Code Playgroud)
并绑定TextBlock
<TextBlock Text="{Binding Path=Breadth, Converter={StaticResource Units}}" Style="{StaticResource Values}"/>
Run Code Online (Sandbox Code Playgroud)
从来没有,我收到以下错误:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement.BindingExpression:路径= IsMetric; 的DataItem = NULL; target元素是'UnitConverter'(HashCode = 62641008); target属性是'IsMetric'(类型'布尔')
我想这是在我设置datacontext之前初始化,因此没有什么可以将IsMetric
属性绑定到.我怎样才能达到预期的效果?
只要Breadth
与IsMetric
具有相同的数据对象的属性,你可以使用一个MultiBinding连同多值转换器:
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource UnitMultiValueConverter}">
<Binding Path="Breadth" />
<Binding Path="IsMetric" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
使用这样的转换器:
public class UnitMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double value = (double)values[0];
bool isMetric = (bool)values[1];
string format = isMetric ? "{0:0.0}" : "{0:0.000}";
return string.Format(format, value);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
您的方法的问题是,当UnitConverter被声明为资源时,它没有DataContext,并且以后永远不会得到它.
还有一件更重要的事情:ValueChanged
回调UnitConverter.IsMetric
是无稽之谈.它再次设置相同的属性,刚刚更改.
归档时间: |
|
查看次数: |
5529 次 |
最近记录: |