简体   繁体   中英

Selected Item Always deselect (C#)

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();

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

Full Sample Codes

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();
}

OUTPUT

输出量

My guess is that you trigger the event again by setting SelectedIndex to -1 , as a result SelectedItem is now null . Anyway, in that case a quick fix is to guard the if statement with a possible null :

var selectedItem = FavoritesListBox.SelectedItem;

if( selectedItem.ToString() != MiniTextBLock.Text)
{
    FavoritesListBox.SelectedIndex = -1;
}

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;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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