【发布时间】:2025-12-29 12:00:07
【问题描述】:
我正在执行一个尝试定义和打开 WPF 窗口的 roslyn 脚本。
除此之外,我的脚本
- 定义附加行为
- 定义了一个 XAML 字符串,基于它我创建了一个 WPF 窗口。在此 XAML 代码中,我想使用脚本中定义的 TextBoxCursorPositionBehavior。
我的脚本 (.csx) 文件看起来类似于
public class TextBoxCursorPositionBehavior : DependencyObject
{
// see http://*.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?
【问题讨论】: