簡體   English   中英

WPF / XAML:如何引用未在任何命名空間中定義的類

[英]WPF/XAML: How to reference class that is not defined within any namespace

我正在執行一個嘗試定義和打開WPF窗口的roslyn腳本。

除此之外,我的腳本

  1. 定義附加行為
  2. 定義一個XAML字符串,基於此我創建一個WPF窗口。 在這個XAML代碼中,我想使用我的腳本中定義的TextBoxCursorPositionBehavior。

我的腳本(.csx)文件看起來類似於

public class TextBoxCursorPositionBehavior : DependencyObject
{
    // see http://stackoverflow.com/questions/28233878/how-to-bind-to-caretindex-aka-curser-position-of-an-textbox
}

public class MyGui
{
    public void Show()
    {
      string xaml = File.ReadAllText(@"GUI_Definition.xaml");

      using (var sr = ToStream(xaml))
      {
        System.Windows.Markup.ParserContext parserContext = new System.Windows.Markup.ParserContext();
        parserContext.XmlnsDictionary.Add( "", "http://schemas.microsoft.com/winfx/2006/xaml/presentation" );
        parserContext.XmlnsDictionary.Add( "x", "http://schemas.microsoft.com/winfx/2006/xaml" );
        parserContext.XmlnsDictionary.Add("i","clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity");

        // ?? How  can i define this properly?
        parserContext.XmlnsDictionary.Add("behaviors", "clr-namespace:;assembly=" + typeof(TextBoxCursorPositionBehavior).Assembly.FullName);

        var window = (System.Windows.Window)XamlReader.Load(sr, parserContext);
        window.ShowDialog();
      }
    }
}

並假設GUI_Definition.xaml看起來像

<Window x:Class="System.Windows.Window" Height="300" Width="300" >
<Grid>
  <!-- how can i attach my behavior here properly? -->
  <TextBox behaviors:TextBoxCursorPositionBehavior.TrackCaretIndex="True"/>
</Grid>
</Window>

但問題是,如何在XAML中正確引用TextBoxCursorPositionBehavior?

Roslyn不允許在腳本文件中使用命名空間,因此TextBoxCursorPositionBehavior必須在命名空間之外定義(即我認為它將落入全局命名空間)。

但是,我怎樣才能在XAML中引用它? 我嘗試使用“clr-namespace :; assembly =”+ typeof(TextBoxCursorPositionBehavior).ToString()來定義命名空間引用,但這不起作用。 簡單地說“clr-namespace:”(即沒有匯編引用)也不起作用。

有沒有辦法從XAML定義中引用TextBoxCursorPositionBehavior?

在您的代碼而不是匯編中使用:

typeof(TextBoxCursorPositionBehavior).ToString()

這不是程序集名稱。 將其更改為:

parserContext.XmlnsDictionary.Add("behaviors", "clr-namespace:;assembly=" + Assembly.GetExecutingAssembly().FullName);

它應該工作正常(至少適合我,但我不測試Roslyn腳本,但只是常規的WPF應用程序)。

我想我知道發生了什么...... Roslyn為腳本創建了一個自定義的Submission類型,似乎所有東西 - 包括TextBoxCursorPointerBehavior的定義 - 都是這個提交類型的子類。 也就是說,

        var inst = new TextBoxCursorPositionBehavior();
        string typeName = inst.GetType().FullName;

typeName不是“TextBoxCursorPointerBehavior”,而是“Submission#0 + TextBoxCursorPositionBehavior”。

同時,我不能從XAML中引用它(例如通過行為:提交#0 + TextBoxCursorPositionBehavior.TrackCaretIndex =“True”),因為它不會正確解析名稱(#是一個無效的標記)。

從理論上講,有可能將Roslyn的提交類型重命名為可通過XAML實際引用的內容 - 但在我的情況下,我不能這樣做。

遺憾的是,目前我沒有看到任何解決我的問題的方法,除了可能將此代碼外包給一個單獨的預編譯DLL(但這不​​是腳本編寫的重點)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM