绑定到WPF中的扩展方法

Joh*_*ith 7 c# wpf extension-methods binding

我在C#中有一个简单的类:

public class Dog {
    public int Age {get; set;}
    public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个像这样的扩展方法:

public static class DogExt {
    public static string BarkYourName(this Dog dog) {
        return dog.Name + "!!!";
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将BarkYourName方法的结果绑定到wpf组件?

基本上:有什么方法可以将它绑定到扩展方法?

Spo*_*xus 9

不,您无法绑定到扩展方法.您可以绑定到Name-object的-property Dog并使用转换器.

要创建转换器,请创建实现该IValueConverter接口的类.您将只需要单向转换(从模型到视图),因此Convert只需要实现该方法.ConvertBack转换器不支持该方法,因此抛出一个NotSupportedException.

public class NameToBarkConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var dog = value as Dog;
        if (dog != null)
        {
            return dog.BarkYourName();
        }
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以按如下方式使用转换器:

<Grid>
    <Grid.Resources>
        <NameToBarkConverter x:Key="NameToBarkConverter" />
    </Grid.Resources>
    <TextBlock Text="{Binding Name, Converter={StaticResource NameToBarkConverter}}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

有关转换器的更多信息,请参阅MSDN:IValueConverter.


Nit*_*tin 5

无法绑定到方法。您可以在类中创建属性,Dog如下所示并绑定到它

public string NameEx
    {
        get
        {
            return this.BarkYourName();
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果您想保持Name同步NameEx,只需在 -property 的 setter 中引发PropertyChanged-event 即可。NameExName