2011-06-09 58 views
1

我有一個委託類型:如何在Xaml中使用委託類型屬性?

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) 
    { 
     ... 
    } 
} 

如果我在codebehind中設置屬性,一切都很好。但是,如果我將它設置在XAML:

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

當我運行我的應用程序我得到一個異常:「‘CheckFormatDelegate’類型不具有公共的TypeConverter類。」有沒有人知道是否有一組內置的轉換器/標記擴展,如用於RoutedEvent的擴展?或者還有其他解決方法嗎?

+0

可能重複(http://stackoverflow.com/questions/5146946/binding-of-static-methode-function-to-funct-property-in-xaml) – 2011-06-09 07:17:26

+0

看起來這個解決方案實際上適用於我。如果你可以把它放在你的答案中,我會接受它。謝謝! – 2011-06-09 07:37:24

回答

3

您所得到的錯誤是因爲它試圖將字符串轉換爲對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

+0

我試過的第一件事是x:Static。我認爲你的意思是這樣的: 這不會編譯。編譯器抱怨它找不到FormatFilterDigits。該文檔指出,您只能在某些項目上使用x:Static,並且我不相信方法是允許的。 – 2011-06-09 06:29:33

+0

我upvoted也。謝謝! – 2011-06-09 07:43:29

0

簡單的方法是使用一個接口,而不是委託

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 Func鍵 財產]的

+0

我不知道這是如何幫助。我不知道Xaml中的類。無論如何,我真的想堅持代表,因爲這種方法會迫使我爲所有的格式檢查器聲明幾十個類。 – 2011-06-09 06:40:46