【问题标题】:XAML access method in code behind [duplicate]代码中的 XAML 访问方法 [重复]
【发布时间】:2011-05-30 03:13:41
【问题描述】:

可能重复:
Bind to a method in WPF?

有没有一种简单的方法可以从我的 XAML 代码中访问方法?

我见过使用 ObjectDataProvider 的解决方案,但据我了解,它们会创建给定类型的新实例并调用此对象的方法。这对我没有用,因为我需要调用我的类的实际代码(数据上下文对方法很重要!)...

Route.xaml.cs: public string GetDifficultyName(int id);

Route.xaml: Displays a list of routes

每个路由都有一个属性“DiffId”,必须将其传递给上述方法,并且必须将结果设置为文本框的值 -> 将 id 解析为人类可读的描述。

【问题讨论】:

  • 检查 my answer here,它显示了如何绑定到 WPF XAML 中的方法。

标签: c# wpf xaml code-behind


【解决方案1】:

执行此操作的一种简单方法是将ValueConverter 实例公开为Window(或Control 或其他)中的资源,该资源已在您的代码隐藏中适当地初始化以调用方法你需要。

例如:

[ValueConversion(typeof(object), typeof(string))]
public class RouteDifficultyNameConverter : IValueConverter
{
    private readonly IMyMethodProvider provider;

    public RouteDifficultyNameConverter(IMyMethodProvider provider)
    {
        this.provider = provider;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return provider.GetDifficultyName((int)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

这当然不是一个完整的转换器,但你明白了。

在你的代码隐藏构造函数中:

    this.Resources.Add("routeDifficultyConverter",
                       new RouteDifficultyNameConverter(this));
    this.InitializeComponent();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多