gpt4 book ai didi

c# - 将转换器绑定(bind)为内部类?

转载 作者:太空狗 更新时间:2023-10-29 19:47:37 26 4
gpt4 key购买 nike

我有一个使用绑定(bind)转换器的 UserControl。我已将转换器设为

public partial class MyPanel : UserControl
{
public class CornerRadiusConverter : IValueConverter
{

如何从 XAML 中引用 Converter 类?以下不起作用:

<controls:MyPanel.CornerRadiusConverter x:Key="CornerRadiusConverter" />

它给出了这个错误:

The tag 'LensPanel.CornerRadiusConverter' does not exist in XML namespace 'clr-namespace:MyApp.Windows.Controls'

最佳答案

我又在思考这个问题,我想出了一个类似于 Dennis 的解决方案:创建一个“代理”转换器类,带有一个 Type 属性,它将创建实际转换器的实例并将转换委托(delegate)给它.

public class Converter : IValueConverter
{
private Type _type = null;
public Type Type
{
get { return _type; }
set
{
if (value != _type)
{
if (value.GetInterface("IValueConverter") != null)
{
_type = value;
_converter = null;
}
else
{
throw new ArgumentException(
string.Format("Type {0} doesn't implement IValueConverter", value.FullName),
"value");
}
}
}
}

private IValueConverter _converter = null;
private void CreateConverter()
{
if (_converter == null)
{
if (_type != null)
{
_converter = Activator.CreateInstance(_type) as IValueConverter;
}
else
{
throw new InvalidOperationException("Converter type is not defined");
}
}
}

#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
CreateConverter();
return _converter.Convert(value, targetType, parameter, culture);
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
CreateConverter();
return _converter.ConvertBack(value, targetType, parameter, culture);
}

#endregion
}

你可以这样使用它:

<Window.Resources>
<my:Converter x:Key="CornerRadiusConverter" Type="{x:Type controls:MyPanel+CornerRadiusConverter}"/>
</Window.Resources>

关于c# - 将转换器绑定(bind)为内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863180/

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