这是我的场景:我有一个制表符控件,其ItemsSource绑定到另一个类的集合。 DataTemplate中的一个控件是自定义TextEditor。我需要在支持代码中生成这个,因为我做了一些自定义。
这是我的XAML:
<TabControl x:Name="tabControl">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Category}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<text:TextEditor Buffer="{Binding Buffer}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
以下是我想要为每个TextEditor调用的内容(而不是像当前那样只从itemsSource设置Buffer):
public TextEditor CreateTextEditor(TextBuffer buffer, string category)
{
var editor = new TextEditor() { FontFamily = new FontFamily("Consolas"), FontSize = 12, IsReadOnly = true, AutoScroll = true };
editor.SetBinding(TextEditor.ForegroundProperty, Theme.CreateBinding("ControlDisabledForegroundBrush"));
if (this.loggingService == null)
{
editor.Buffer = TextBuffer.FromText("Unable to get logging service; logging output unavailable.");
}
else
{
editor.Buffer = buffer;
editor.MoveCaret(editor.MapToCoordinate(editor.Buffer.TextData.End), false);
var contextMenu = new ContextMenu();
var item = new MenuItem { Header = "Clear All" };
item.Click += (o, e) =>
{
using (var pencil = loggingService.Buffer.GetPencil())
{
pencil.Write(new TextLocation(0, 0), loggingService.Buffer.TextData.End, TextData.Empty);
}
};
contextMenu.Items.Add(item);
editor.ContextMenu = contextMenu;
}
return editor;
}
有没有办法可以用这段代码初始化TextEditor?我可以使用{Binding Buffer}和{Binding Category}来访问我需要传递给方法的两个参数。
答案 0 :(得分:1)
我最终继承了TabControl并重写了PrepareContainerForItemOverride()
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
TabItem tabItem = (TabItem)element;
LogBufferMapping bufferMapping = (LogBufferMapping)item;
tabItem.Header = bufferMapping.Category;
tabItem.Content = CreateTextEditor(bufferMapping.Buffer, bufferMapping.Category);
}
希望如果有人想要做类似的事情,这会有所帮助。