繁体   English   中英

MVVM - 在ListBox中选择项目,双击并生成粗体

[英]MVVM - Select item in ListBox with Double click and make bold

我想这样做,所以需要双击才能选择ListBox中的项目。 此选定项应始终为粗体。 我知道SelectedItem属性将不再反映我作为选定项目处理的项目,因此我之前用于使所选项目变为粗体的XAML将不再起作用。

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="FontWeight" Value="Bold"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

我已经研究了如何使用MVVM处理双击,并得出结论可以使用后面的代码和MouseDoubleClick事件。

private void lbProfiles_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    _viewModel.SelectedProfile = ((ListBox)sender.)SelectedItem as MyProfile;
    //What should go here?
}

我的视图模型将具有一个我认为将在上面的方法中设置的SelectedProfile属性。 无论如何在XAML中绑定SelectedProfile还是必须在后面的代码中进行管理? 另外,这个项目加粗的最佳方法是什么?


编辑1:

我最后调整了Rachel的答案,以便只需单击一下该项就会突出显示但不会被选中。 这样,视图模型可以具有SelectedItem属性和HighlightedItem属性。

private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount < 2)
        e.Handled = true;

    var clickedItem = ((ContentPresenter)e.Source).Content as MyProfile;

    if (clickedItem != null)
    {
        //Let view model know a new item was clicked but not selected.
        _modelView.HighlightedProfile = clickedItem;

        foreach (var item in lbProfiles.Items)
        {
            ListBoxItem lbi = 
                lbProfiles.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;

            //If item is not displayed on screen it may not have been created yet.
            if (lbi != null)
            {
                if (item == clickedItem)
                {
                    lbi.Background = SystemColors.ControlLightBrush;
                }
                else
                {

                    lbi.Background = lbProfiles.Background;
                }
            }
        }
    }
}

仅在DoubleClick上选择项目的最简单方法是,如果ClickCount小于2, 则将 click事件标记为Handled

这也可以让你保持你的Trigger在选中时将文本设置为Bold

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <EventSetter Event="PreviewMouseDown" Handler="ListBoxItem_PreviewMouseDown" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="FontWeight" Value="Bold" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>


private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount < 2)
        e.Handled = true;
}

请记住,这会禁用ListBoxItem上的所有单击事件。 如果您想允许某些单击事件,则必须调整PreviewMouseDown事件,以便不将特定点击标记为已Handled

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM