【问题标题】:Handling Button's Click Command Inside ListView在 ListView 中处理按钮的单击命令
【发布时间】:2017-10-10 15:55:10
【问题描述】:

假设我有一个简单的 ListView,在它的 Gridview 的唯一列中有一个按钮:

<ListView x:Name="SomeListView" ItemsSource="{Binding Whatever}">
    <ListView.View>
        <GridView>
             <GridViewColumn CellTemplate="{StaticResource myCellTemplate}" Header="ColumnHeader"/>
        </GridView>
    </ListView.View>
</ListView>

myCellTemplate 看起来像这样:

<DataTemplate x:Key="myCellTemplate">
    <Viewbox>
        <Button x:Name="mybutton" Command="{Binding myClickCommand}" Content="{Binding btnBinding}"></Button>
    </Viewbox>
</DataTemplate>

在我的虚拟机中使用 myClickCommand 是一个 ICommand。在这一点上,一切都是笨拙的,用户单击我的按钮会调用 myClickCommand,正如您所期望的那样。现在,我想为我的行添加一些鼠标悬停样式,所以我添加了这样的 ItemContainerStyle:

<ListView x:Name="SomeListView" ItemContainerStyle="{StaticResource myItemStyle}" ItemsSource="{Binding Whatever}">
    ...
</ListView>

myItemStyle 为:

<Style x:Key="myItemStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Grid>
                    <Border x:Name="borderMain" BorderThickness="1" BorderBrush="Transparent">
                        <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <Rectangle x:Name="rectGlass" Fill="LightGray" Opacity=".2" Visibility="Hidden"></Rectangle>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="borderMain" Property="BorderBrush" Value="DarkGray" />
                        <Setter TargetName="rectGlass" Property="Visibility" Value="Visible"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

此时用户的点击并没有触发myClickCommand,大概是因为事件没有路由到按钮。有什么方法可以实现吗?

【问题讨论】:

    标签: wpf xaml datatemplate controltemplate


    【解决方案1】:

    您的矩形 (rectGlass) 位于按钮顶部。该按钮没有收到点击事件,因为它实际上从未被点击过。

    【讨论】:

    • 嗯。好的,我看到我可以更改 myItemStyle 中的控件顺序,以将边框“放在”rectGlass Rectangle 的“顶部”。这允许单击按钮,但在风格上并不是我想要的。无论如何,这回答了这个问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多