[英]TabItem Binding WPF
我刚刚学习WPF,我可以使用一些帮助。 我有一个使用TabControl并动态生成新标签的应用程序,在每个标签上我有一个TextBox,现在我想在工具栏中添加一个撤销按钮,它不是标签的一部分(像VisualStudio一样)。 撤消按钮只能在活动选项卡上的TextBox上工作,如果没有选项卡或撤消无法执行,它将被禁用。 我不知道如何绑定这两个项目(选项卡内容有自己的xaml文件)。
我唯一成功的是将一个click eventHandler添加到MenuItem,然后按名称在活动选项卡上找到文本框,但现在我不能像我希望的那样启用/禁用。
我希望这是可以理解的。 谢谢你的帮助
我举了一个例子来说明这种情况下的“正确的WPF方式” 。 同样,它可能与您已有的代码不匹配,但它应该为您提供有关如何调整代码的一些想法。 首先,代码隐藏:
public partial class TabItemBinding : Window
{
public ObservableCollection<TextItem> Items { get; set; }
public TabItemBinding()
{
Items = new ObservableCollection<TextItem>();
Items.Add(new TextItem() { Header = "1", Content = new TextBox() { Text = "First item" } });
Items.Add(new TextItem() { Header = "2", Content = new TextBox() { Text = "Second item" } });
Items.Add(new TextItem() { Header = "3", Content = new TextBox() { Text = "Third item" } });
InitializeComponent();
}
}
public class TextItem
{
public string Header { get; set; }
public FrameworkElement Content { get; set; }
}
这里没什么了不起的,我只是创建一个模型类并设置该类的集合。 真正的善良发生在XAML中:
<Window x:Class="TestWpfApplication.TabItemBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TabItemBinding" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ToolBar Grid.Row="0">
<Button Command="Undo">Undo</Button>
</ToolBar>
<TabControl Grid.Row="1" ItemsSource="{Binding Items}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}"/>
<Setter Property="Content" Value="{Binding Content}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
我将Button
到ApplicationCommands.Undo
,只要我们有一个活动的编辑TextBox
,它将自动为我们处理撤消。 TabControl
本身绑定到我们在代码隐藏中创建的集合,它将提供标题和一些要编辑的文本。 我们所做的任何编辑都是可撤销的。 结果:
截图http://img706.imageshack.us/img706/2866/tabitembinding.png
顺便说一句,重要的是要注意,如果没有活动的编辑上下文,undo命令将自动禁用自身。 因此,如果没有标签页,我们将禁用它而不需要任何额外的代码。
使用WPF内置的Command系统可以更轻松地完成您的工作。 基本上,它有一个内置的“CanExecute”事件,您可以在其中检查TabControl的选定页面等等。 没有任何示例代码可以提供具体示例很难,但希望这会让您走上正确的道路。
您可能对WPF应用程序框架(WAF)项目的Writer示例应用程序感兴趣。 它显示了一个带Tabbed MDI(类似于Visual Studio)的简单编辑器,它实现了Undo / Redo功能。 这可能正是您正在寻找的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.