【问题标题】:How to use a delegate type property in Xaml?如何在 Xaml 中使用委托类型属性?
【发布时间】:2011-09-11 10:21:17
【问题描述】:

我有一个委托类型:

public delegate bool CheckFormatDelegate(int row, int col, ref string text);

这已在 Xaml 对象的属性中使用:

public virtual CheckFormatDelegate CheckFormat { get; set; }

我将属性值设置为一组委托中的一个,例如:

public class FCS
{
    public static bool FormatDigitsOnly(int row, int col, ref string text)
    {
        ...
    }
}

如果我在代码隐藏中设置属性,一切都很好。但是,如果我在 Xaml 中设置它:

<mui:DXCell CheckFormat="mui:FCS.FormatDigitsOnly"/>

当我运行我的应用程序时,出现异常:“'CheckFormatDelegate' 类型没有公共 TypeConverter 类。”。有谁知道是否有一组内置的转换器/标记扩展,例如用于 RoutedEvent 的转换器/标记扩展?还是有其他方法可以解决这个问题?

【问题讨论】:

标签: c# wpf


【解决方案1】:

您遇到的错误是因为它试图将字符串转换为对 XAML 编译器有意义的内容。您也许可以为它创建一个类型转换器(通过反射实现),但是有更简单的方法可以解决这个问题。

使用x:Static 标记扩展。

<object property="{x:Static prefix:typeName.staticMemberName}" ... />

请参阅 MSDN 文档:

http://msdn.microsoft.com/en-us/library/ms742135.aspx

根据那个页面:

...大多数有用的静态属性都支持类型转换器,无需 {x:Static} ...

我猜你的自定义委托没有,并且需要你使用x:Static

编辑

我试过了,就像你提到的那样,它似乎不适用于方法。但它确实对属性起作用。这是一个解决方法:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <local:Class1 CheckFormat="{x:Static local:FCS.FormatDigitsOnly}" />
</Window>

namespace WpfApplication1
{
    public delegate bool CheckFormatDelegate(int row, int col, ref string text);

    public class Class1
    {
        public virtual CheckFormatDelegate CheckFormat { get; set; }
    }

    public class FCS
    {
        private static bool FormatDigitsOnlyImpl(int row, int col, ref string text)
        {
            return true;
        }

        public static CheckFormatDelegate FormatDigitsOnly
        {
            get { return FormatDigitsOnlyImpl; }
        }
    }
}

编辑 2

我不想窃取他们的答案(所以请给他们投票,除非您更喜欢属性解决方法),但这里有一个问题可以为您提供更好的解决方案:

Binding of static method/function to Func<T> property in XAML

【讨论】:

  • 我尝试的第一件事是 x:Static。我假设您的意思是这样的: 这不会编译。编译器抱怨它找不到 FormatFilterDigits。文档声明您只能在某些项目上使用 x:Static,我认为不允许使用方法。
【解决方案2】:

最简单的选择是使用接口而不是委托

public interface IFormatChecker
{
    bool CheckFormat(int row, int col, ref string text);
}

public sealed class CheckFormatByDelegate : IFormatChecker
{
    ...
}

public class FCS
{
    public static readonly IFormatChecker FormatDigitsOnly = new CheckFormatByDelegate();
}

<mui:DXCell CheckFormat="{x:Static mui:FCS.FormatDigitsOnly}"/>

如果你不喜欢这个界面,我想你可以创建自己的自定义 MarkupExtension

【讨论】:

  • 我不确定这有什么帮助。据我所知,您也不能在 Xaml 中分配类。无论如何,我真的很想坚持使用委托,因为这种方法会迫使我为所有格式检查器声明数十个类。
猜你喜欢
  • 2021-10-18
  • 2017-10-20
  • 1970-01-01
  • 2018-05-10
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多