gpt4 book ai didi

c# - IValueConverter - 传递参数,这是我的自定义控件的属性

转载 作者:行者123 更新时间:2023-12-03 19:34:03 25 4
gpt4 key购买 nike

我为自定义控件创建了一个 .cs 类,其中包含以下属性:

  //Property which is defining the unit of the textblock in the Ringslice
public Units Unit
{
get { return (Units)GetValue(UnitProperty); }
set { SetValue(UnitProperty, value); }
}

// Using a DependencyProperty as the backing store for Unit. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UnitProperty =
DependencyProperty.Register("Unit", typeof(Units), typeof(RingPresenter), new PropertyMetadata(Units.Degree));

在同一个类中我定义了单位:

     public enum Units
{
Percent,
Degree,
Time
}

现在,在 generic.xaml 文件中,我得到了一个 Textblock,该文本 block 绑定(bind)到同一个 .cs Control 类中的另一个 DependencyProperty,该类称为 Angle - 角度应该以正确的格式显示,因为我使用的是 ValueConverter,它应该返回基于 Unit 属性的值。

我的数据绑定(bind)工作正常,但我遇到了 ValueConverter 的问题 - 最后一个参数很重要!

Text="{Binding Mode=TwoWay, ElementName=ringSlice, Path=EndAngle, Converter={StaticResource DoubleDegreesToInt}, ConverterParameter={Binding RelativeSource={RelativeSource TemplatedParent}, Path=Unit}}"

访问 ValueConverter 类中的参数会引发 NullReferenceException - 这是值转换器的代码:

object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
{
Debug.WriteLine(targetType.ToString()); //returning System.String
Debug.WriteLine(parameter.ToString()); //EXCEPTION
return Convert.ToInt32(value); //Is working fine without parameters
}

我做错了什么?我该如何解决这个问题?谨此致谢!

最佳答案

无法将 ConverterParameter 绑定(bind)到 IValueConverter。解决方案是使用如描述的 MultiValueConverter here .

诀窍是将您的信息打包到一个对象中并绑定(bind)属性,如下所示:

<TextBlock>
<TextBlock.Text>
<MutliBinding Converter="{StaticResource myConverter}">
<MultiBinding.Bindings>
<Binding Path="ABC" />
<Binding Path="DEF" />
</MultiBinding.Bindings>
</MultiBinding>
</TextBlock.Text>
</TextBlock>

您的 MultiValueConverter 使用如下属性:

public class MyConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (double)values[0] + " " + (double)values[1];
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("Not implemented");
}
}

编辑:

因为多重绑定(bind)在通用 Windows 应用程序中是不可能的 Damir描述了一种使用 Cimbalino Multibinding Behavior 的方法.

关于c# - IValueConverter - 传递参数,这是我的自定义控件的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37731075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com