所选项目始终取消选择(C#)

时间:2017-10-14 14:15:50

标签: c# uwp

我正在实现一个列表框,当我在列表框中选择一个项目时,它出现在文本块“MiniTextBlock”上,但是我希望手动更改文本块文本或者文本块文本不等于列表框中的选定项目然后,应从列表框中取消选择所选项目。

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文本和所选项目相同,也会取消选择。

完整示例代码

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

2 个答案:

答案 0 :(得分:2)

我的猜测是,通过将SelectedIndex设置为-1来再次触发 事件,因此现在SelectedItem已成为null if。无论如何,在这种情况下,快速解决方法是保护 null语句并使用var selectedItem = FavoritesListBox.SelectedItem; if(selectedItem != null && selectedItem.ToString() != MiniTextBLock.Text) { FavoritesListBox.SelectedIndex = -1; }

{{1}}

答案 1 :(得分:2)

由于您未将来源绑定到ListBox,因此SelectedItem实际上是ListBoxItem,而不是string。您需要向下钻取并找到如下所示的实际文本:

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