【问题标题】:How to delete a Template on a Button click如何在单击按钮时删除模板
【发布时间】:2014-06-16 13:47:05
【问题描述】:

我有ControlTemplate,它被用作ListBox 中的资源,我正在尝试删除模板,即在Button 点击时将其从ListBox 中完全删除 这是模板的代码

 <ControlTemplate x:Key="tasktemplate1">
            <Canvas Height="50" Width="850">
                <Label Content="{Binding XPath=task[1]/name}"  Height="30" Width="170" Canvas.Top="10" Canvas.Left="150" Background="LightGray">
                </Label>
                <TextBox Height="30" Width="120" Canvas.Top="10" Canvas.Left="370" Background="AliceBlue"></TextBox>
                <Label Canvas.Left="500" Canvas.Top="10">$</Label>
                <Button Click="deletebuttonclick" Canvas.Top="12" Height="10" Width="30" Canvas.Left="600" ></Button>
            </Canvas>
        </ControlTemplate>

这是ListBox的代码

 <TabItem>
        <Canvas Height="700" Width="850">
            <ListBox  x:Name="listBox" Height="700" Width="850">
                <ListBoxItem DataContext="{Binding Source={StaticResource TaskList}}" Template="{StaticResource tasktemplate1}"/>
            </ListBox>
        </Canvas>
    </TabItem>

后面的代码是Button点击

    private void deletebuttonclick(object sender,RoutedEventArgs e)
    {
       var r=listBox.FindResource("tasktemplate1");
       listBox.Items.Remove(r);
    }

我哪里出错了,需要帮助,谢谢。

【问题讨论】:

  • 删除模板后会发生什么?
  • 它必须从列表框中删除

标签: c# wpf listbox controltemplate


【解决方案1】:

ControlTemplate 只是控件外观的可视化表示。

因此,您需要从 Items 集合而不是 Template 中删除项目 (ListBoxItem)。由于模板化控件被移除,模板会自动被移除。

private void deletebuttonclick(object sender,RoutedEventArgs e)
{
   listBox.Items.RemoveAt(0);
   // listBox.Items.Clear(); OR in case want to clear all listBoxItems, use Clear
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多