所选项目始终取消选择 (C#) [英] Selected Item Always deselect (C#)

查看:21
本文介绍了所选项目始终取消选择 (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个列表框,当我在列表框中选择一个项目时,它会出现在文本块MiniTextBlock"上,但我想要手动更改文本块文本或文本块文本不等于列表框中选定的项目然后,应从列表框中取消选择该选定项.

I am implementing a list box, when i select an item in list box it appears on a text block "MiniTextBlock" , but i want when text block text is changed manually or textblock text is not equal to selected item in list box then, that selected item should be deselected from list box.

DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.4) };
timer.Tick += delegate (object sender, object e)
{

    if(selectedItem != null && selectedItem.ToString() != MiniTextBlock.Text)
    {
        FavoritesListBox.SelectedIndex = -1;
    }
};
timer.Start();

一切看起来都正确,但即使 Textblock 文本和所选项目相同,它也会取消选择.

every thing looks correct but it is deselect even if Textblock text and selected item is same.

完整示例代码

XAML

<StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <TextBlock Name="MiniTextBlock" Text="35" FontSize="50" VerticalAlignment="Top" HorizontalAlignment="Center"/>

        <ListBox Name="FavoritesListBox" VerticalAlignment="Center">
            <ListBoxItem>
                <TextBlock Text="36" FontSize="30"/>
            </ListBoxItem>
            <ListBoxItem>
                <TextBlock Text="35" FontSize="30"/>
            </ListBoxItem>
            <ListBoxItem>
                <TextBlock Text="34" FontSize="30"/>
            </ListBoxItem>
        </ListBox>
    </StackPanel>

C#

public MainPage()
{
    this.InitializeComponent();
    DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.4) };
    timer.Tick += delegate (object sender, object e)
    {
        var selectedItem = FavoritesListBox.SelectedItem;

        if (selectedItem != null && selectedItem.ToString() != MiniTextBlock.Text)
        {
            FavoritesListBox.SelectedIndex = -1;
        }
    };
    timer.Start();
}

输出

推荐答案

由于您没有将源绑定到 ListBoxSelectedItem 实际上是一个 ListBoxItem,而不是 string.您需要向下钻取并找到这样的实际文本:

Since you're not binding a source to your ListBox, the SelectedItem is actually a ListBoxItem, not a string. You'll need to drill down and find the actual text like this:

timer.Tick += delegate (object sender, object e)
{
    var selectedItem = (ListBoxItem)FavoritesListBox.SelectedItem;

    if (selectedItem == null)
    {
        return;
    }

    var tb = (TextBlock)selectedItem.Content;

    if (tb.Text != MiniTextBlock.Text)
    {
        FavoritesListBox.SelectedIndex = -1;
    }
};

这篇关于所选项目始终取消选择 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆