[英]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. 我正在实现一个列表框,当我在列表框中选择一个项目时,它会出现在文本块“ 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();
every thing looks correct but it is deselect even if Textblock text and selected item is same. 每件事看起来都是正确的,但是即使Textblock文本和所选项目相同,也会取消选择。
Full Sample Codes 完整的示例代码
XAML 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# 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
. 我的猜测是,您可以通过将SelectedIndex
设置为-1
来再次触发事件 ,结果SelectedItem
现在为null
。 Anyway, in that case a quick fix is to guard the if
statement with a possible null
: 无论如何,在这种情况下,一种快速的解决方案是使用可能的null
保护 if
语句:
var selectedItem = FavoritesListBox.SelectedItem;
if(selectedItem != null && 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
. 由于您没有将源绑定到ListBox
,所以SelectedItem
实际上是一个ListBoxItem
,而不是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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.