WPF/XAML:如何参考在任何名称空间中未定义的类别



我正在执行一个试图定义和打开WPF窗口的Roslyn脚本。

除其他外,我的脚本

  1. 定义附属行为
  2. 定义一个XAML字符串,基于我创建WPF窗口。在此XAML代码中,我想使用我脚本中定义的TextBoxCursorPositorPositorPositionBehavior。

我的脚本(.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中正确引用TextBoxCursorPositorPositionBehavior?

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应用程序)。

我想我知道发生了什么……罗斯林为脚本创建了自定义提交类型,并且似乎所有内容 - 包括TextBoxCursorPointerbehavior的定义 - 是此提交类型的子类。即,

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

typename不会是" textboxcursorpointerbehavior",而是"提交#0 textboxcursorpositionbehavior"。

同时,我无法从XAML引用此内容(例如,通过行为:提交#0 TextBoxCursorPositionBehavior.TrackCaretIndex =" true"),因为它无法正确分析该名称(#是无效的soken soken)。

从理论上讲,可能可以将罗斯林的提交类型重命名为实际上可以通过XAML引用的事物 - 但是我无法做到。

不幸的是,目前这意味着我对我的问题没有任何解决方案,除了将此代码外包给单独的预编译的DLL(但这也不是脚本编写的重点)

最新更新