c# - 绑定(bind)到 WPF 中的扩展方法

标签 c# wpf binding extension-methods

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

public class Dog {
    public int Age {get; set;}
    public string Name {get; set;}
}

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

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

有什么方法可以将 BarkYourName 方法的结果绑定(bind)到 wpf 组件吗?

基本上:有没有办法将它绑定(bind)到扩展方法?

最佳答案

不,您不能绑定(bind)到扩展方法。您可以绑定(bind)到 Dog 对象的 Name 属性并使用转换器。

要创建转换器,请创建一个实现 IValueConverter 接口(interface)的类。您将只需要一种单向转换(从模型到 View ),因此只需要实现 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();
    }
}

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

<Grid>
    <Grid.Resources>
        <NameToBarkConverter x:Key="NameToBarkConverter" />
    </Grid.Resources>
    <TextBlock Text="{Binding Name, Converter={StaticResource NameToBarkConverter}}" />
</Grid>

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

关于c# - 绑定(bind)到 WPF 中的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484123/

相关文章:

wpf - 如何防止 ComboBox 中的 NewItemPlaceholder 行绑定(bind)到与 WPF 中的 DataGrid 相同的 DataTable

python - YouTube Python API

C# 标志与 FlagsAttribute

c# - 无法在 Windows XP 机器上启动 wpf 应用程序

c# - 在后面的代码中附加行为

c# - WPF MVVM Bind DataTable to DataGrid 不显示数据

c# - 将列表中的变量绑定(bind)到文本 block INotifyPropertyChanged

c# - ASP.NET 应用程序可以作为本地主机访问,但不能通过 127.0.0.1 访问

c# - 以下代码如何自动线程安全?

c# - MSSQL 查询省略特定行值?