带有删除按钮绑定问题的WPF-Custom TabItem

时间:2016-04-27 10:30:43

标签: c# wpf mvvm dependency-properties tabitem

嗨我'我试图用删除按钮创建一个自定义TabItem,我想将我的viewmodel命令绑定到我的自定义依赖属性' DeleteCommandProperty' 。有人能告诉我我做错了吗?

我的自定义TabControl:

    /// <summary>
    /// TabControl withCustom TabItem
    /// </summary>
    public class MyTabControl:TabControl
    {
        /// <summary>
        /// TabItem override
        /// </summary>
        /// <returns></returns>
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new MyTabItem();
        }
    }

我的自定义TabItem类:

    /// <summary>
    /// Custom TabItem
    /// </summary>
    public class MyTabItem:TabItem
    {
        /// <summary>
        /// Delete Command 
        /// </summary>
        public static DependencyProperty DeleteCommandProperty = DependencyProperty.Register(
           "DeleteCommand",typeof(ICommand),typeof(MyTabItem));

        /// <summary>
        /// Delete
        /// </summary>
        public ICommand DeleteCommand
        {
            get { return (ICommand)GetValue(DeleteCommandProperty); }
            set { SetValue(DeleteCommandProperty, value); }
        }
    }

当我像这样直接绑定DeleteCommand时,我的ViewModel中的Command被执行

 <customControls:MyTabControl>
            <customControls:MyTabItem Header="Test" DeleteCommand="{Binding DeleteStudiengangCommand}" Template="{DynamicResource MyTabItemControlTemplate}"/>
        </customControls:MyTabControl>

尝试通过这样的样式绑定deleteCommand但是它不起作用:

 <Style TargetType="customControls:MyTabItem">
                        <Setter Property="Template" Value="{DynamicResource MyTabItemControlTemplate}"/>
                        <Setter Property="DeleteCommand" Value="{Binding MyDeleteCommand}"/>
                    </Style>



<customControls:MyTabControl ItemsSource="{Binding MyList}" SelectedItem="{Binding SelectedItem}" SelectedIndex="0">
                    <customControls:MyTabControl.ContentTemplate>
                        <DataTemplate>
                            <ItemsControl ItemsSource="{Binding Value}" >
                                <ItemsControl.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <WrapPanel/>
                                    </ItemsPanelTemplate>
                                </ItemsControl.ItemsPanel>
                            </ItemsControl>
                        </DataTemplate>
                    </customControls:MyTabControl.ContentTemplate>
                </customControls:MyTabControl>

1 个答案:

答案 0 :(得分:2)

<强> TL; DR

我怀疑您的DataContext包含MyList中的当前项目(无论它是什么),因此样式设置器无法按计划访问MyDeleteCommand属性。查看visual studio调试器日志,是否记录了绑定异常。

从工作代码演变到发生可能的问题解释的示例。

您似乎在减少示例方面遇到了一些困难,因此根据您提供的信息,我唯一可以提供的是使用StyleTemplateBinding方法的小工作示例用作识别真实问题的基础。 编辑:最后的解释实际上可能是您问题的答案。

请注意,您可能需要更改名称空间以与项目设置相匹配。

<强> MainWindow.xaml

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">

    <Window.Resources>
        <!-- Header template -->
        <ControlTemplate x:Key="MyTabItemControlTemplate" TargetType="{x:Type local:MyTabItem}">
            <!-- Some text and the command button with template binding -->
            <StackPanel Orientation="Horizontal" Background="Aquamarine" Margin="3">
                <ContentPresenter Content="{TemplateBinding Header}" VerticalAlignment="Center" Margin="2"/>
                <Button Content="Delete" Command="{TemplateBinding DeleteCommand}" Margin="2"/>
            </StackPanel>
        </ControlTemplate>

        <!-- Setting the control template and assigning the command implementation -->
        <Style TargetType="{x:Type local:MyTabItem}">
            <Setter Property="Template" Value="{DynamicResource MyTabItemControlTemplate}"/>
            <Setter Property="DeleteCommand" Value="{Binding MyDeleteCommand}"/>
            <Setter Property="Header" Value="Default Header Text"/>
        </Style>
    </Window.Resources>

    <Grid>
        <local:MyTabControl ItemsSource="{Binding MyTabItemList}"/>
    </Grid>
</Window>

<强> MainWindow.xaml.cs

/// <summary>
/// TabControl withCustom TabItem
/// </summary>
public class MyTabControl : TabControl
{
    /// <summary>
    /// TabItem override
    /// </summary>
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new MyTabItem();
    }
}

public class MyTabItem : TabItem
{
    /// <summary>
    /// Delete Command 
    /// </summary>
    public static DependencyProperty DeleteCommandProperty = DependencyProperty.Register(
       "DeleteCommand", typeof(ICommand), typeof(MyTabItem));

    /// <summary>
    /// Delete
    /// </summary>
    public ICommand DeleteCommand
    {
        get { return (ICommand)GetValue(DeleteCommandProperty); }
        set { SetValue(DeleteCommandProperty, value); }
    }
}

public class MyCommand : ICommand
{
    public void Execute(object parameter)
    {
        MessageBox.Show("Hello WPF", "Message");
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged { add { } remove { } }
}

public class MyContext
{
    public ICommand MyDeleteCommand { get; set; }

    public List<object> MyTabItemList { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var list = new List<object>();
        list.Add(new TextBlock() { Text = "Test 1" });
        list.Add(new MyTabItem() { Content = "Test Content 2", Header = "Test Header 2" });
        list.Add(new TabItem() { Content = "Test Content 3", Header = "Test Header 3" });
        this.DataContext = new MyContext()
        {
            MyTabItemList = list,
            MyDeleteCommand = new MyCommand()
        };
    }
}

示例摘要: 您会看到三个不同的选项卡,每个选项卡都有其独特的构建和外观:

  1. 标签项是从GetContainerForItemOverride方法创建的,Header属性的样式设置器指定标题中显示的文本。 MyDeleteCommand绑定不起作用!
  2. 标签项以MyTabItem的形式提供,包含标题和内容值。 Header属性的样式设置器不适用,因为该属性已明确设置。 DeleteCommand属性的样式设置器绑定到MyDeleteCommand的{​​{1}}属性。
  3. 标签项以MyContext的形式提供,因为没有覆盖TabItem,所以它被接受为MyTabControl.IsItemItsOwnContainerOverride的控制项。整个MyTabControl模板不适用。
  4. visual studio中的调试输出提示了第一个标签项的基本问题:

      

    System.Windows.Data错误:40:BindingExpression路径错误:在'object'''TextBlock'(Name ='')'上找不到'MyDeleteCommand'属性。 BindingExpression:路径= MyDeleteCommand; DataItem ='TextBlock'(Name =''); target元素是'MyTabItem'(Name =''); target属性是'DeleteCommand'(类型'ICommand')

    原因是,与第二个标签项不同,当前标签项内容在此方案中成为新的本地MyTabItem,其中项目本身被接受为容器。

    解决方案可以是确保在命令绑定中使用propper上下文:

    假设您为某个合适的父元素指定了名称DataContext,那么您可以访问父x:Name="_this"

    DataContext