1

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:

レイチェルの答えを少し調整して、シングルクリックでアイテムが強調表示されますが、選択されないようにしました。そうすれば、ビュー モデルは 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;
                }
            }
        }
    }
}
4

1 に答える 1

3

項目のみを選択する最も簡単な方法は、 ClickCountが 2 未満であるかのようDoubleClickにクリック イベントをマークすることです。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

于 2012-08-24T16:56:04.443 に答える