我想申请"详细信息"模板列表框" btnDetails"按钮单击。
<Window>
<Window.Resources>
<DataTemplate x:Key="detail">
<TextBlock Text="ABC" Background="Yellow"/>
</DataTemplate>
<Style x:Key="MyItemStyle" TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="Button.IsPressed" Value="True">
<Setter Property="Template" Value="{DynamicResource detail}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ListBox Name="lbDetails" ItemContainerStyle="{Binding MyItemStyle}"></ListBox>
<Button Name="btnDetails">Details</Button>
</StackPanel>
</Window>
我尝试使用上面的代码,但它没有用。
答案 0 :(得分:2)
这是一个示例,当您按下按钮
时,它将修改项目模板使用按钮(按下开关)
<ContentControl>
<ContentControl.Resources>
<DataTemplate x:Key="detail">
<TextBlock Text="ABC"
Background="Yellow" />
</DataTemplate>
</ContentControl.Resources>
<ContentControl.Template>
<ControlTemplate>
<StackPanel>
<ListBox Name="lbDetails">
dummy item
</ListBox>
<Button Name="btnDetails">Details</Button>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsPressed"
Value="True"
SourceName="btnDetails">
<Setter TargetName="lbDetails"
Property="ItemTemplate"
Value="{StaticResource detail}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
我确实将原始控件包装在内容控件的控件模板中,以实现对IsPressed属性的控制
如果你想要一个切换类型的按钮,那么这里是xaml
使用切换(关开关)
<ContentControl>
<ContentControl.Resources>
<DataTemplate x:Key="detail">
<TextBlock Text="ABC"
Background="Yellow" />
</DataTemplate>
</ContentControl.Resources>
<ContentControl.Template>
<ControlTemplate>
<StackPanel>
<ListBox Name="lbDetails">
dummy item
</ListBox>
<ToggleButton Name="btnDetails">Details</ToggleButton>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsChecked"
Value="True"
SourceName="btnDetails">
<Setter TargetName="lbDetails"
Property="ItemTemplate"
Value="{StaticResource detail}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
在上面的xaml中,我使用切换按钮代替常规按钮来保持详细信息
答案 1 :(得分:1)
<强>的Xaml 强>
<Window.Resources>
<DataTemplate x:Key="detail">
<TextBlock Text="{Binding text}" Background="{Binding bg}"/>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox Name="lbDetails" ItemTemplate="{StaticResource detail}"/>
<Button Name="btnDetails" Height="35" Content="Add" Click="btnDetails_Click_1"/>
</StackPanel>
<强> c#中强>
public partial class MainWindow : Window
{
ObservableCollection<listboxData> lst = new ObservableCollection<listboxData>();
public MainWindow()
{
InitializeComponent();
lbDetails.ItemsSource = lst;
}
private void btnDetails_Click_1(object sender, RoutedEventArgs e)
{
lst.Add(new listboxData("Textblock" + lst.Count, new SolidColorBrush(Colors.YellowGreen)));
}
}
public class listboxData
{
public string text { get; set; }
public SolidColorBrush bg { get; set; }
public listboxData(string text, SolidColorBrush bg)
{
this.text = text;
this.bg = bg;
}
}