Dro*_*onz 2 wpf listview selecteditem selection
我查看了几个相关的答案,并确定我可以通过设置lstData.SelectedIndex = -1以编程方式清除选择; 但是,当我在启动时设置数据上下文后立即执行此操作时,它会以某种方式工作并设置为选择列表中的第一个元素.
我也尝试将设置添加到XAML中,-1实际上是Visual Studio的默认值,但除非您设置它,否则它实际上不在XAML中.即:
<ListView Margin="6,6,6,203"
IsSynchronizedWithCurrentItem="True"
x:Name="lstData"
ItemsSource="{Binding}"
SelectionChanged="lstData_SelectionChanged"
HorizontalContentAlignment="Right"
ItemContainerStyle="{StaticResource ItemContStyle}"
SelectedIndex="-1">
Run Code Online (Sandbox Code Playgroud)
但这也没有效果.
另外,令人着迷的是,如果我把lstData.SelectedIndex = 3; 在我的LoadData方法中,它将在选择第三个成员时开始设置.
这是我的相关窗口加载代码:
public Window1()
{
InitializeComponent();
// Set start and end dates to day after tomorrow, and
// the next day, by default:
StartDate = DateTime.Now.AddDays(1);
EndDate = StartDate.AddDays(2);
txtStartDate.Text = StartDate.ToShortDateString();
txtEndDate.Text = EndDate.ToShortDateString();
LoadData();
}
public void LoadData()
{
App.RefreshMembers();
App.CalculateNeededMeals(StartDate, EndDate);
// Bind the ListBox to our ObserveableCollection
LayoutRoot.DataContext =
App.db.PFW_Members.OrderBy("FullName",true).OrderBy("CancelDate",true);
lstData.SelectedIndex = -1;
}
Run Code Online (Sandbox Code Playgroud)
并且在其他情况下调用LoadData(),在这种情况下,它会清除选择.只是不是窗口第一次加载.好像,有一些初始化线程没有真正完成并且如果在启动时为-1则将其设置为0.
哦,是的,我确实有一个选择更改处理程序,但它不会更改选择,即:
private void lstData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstData.SelectedItem == null)
{
btnReactivate.IsEnabled = false;
btnDeactivate.IsEnabled = false;
}
else
{
if (((PFW_Member)lstData.SelectedItem).CancelDate == null)
{
btnReactivate.IsEnabled = false;
btnDeactivate.IsEnabled = true;
}
else
{
btnReactivate.IsEnabled = true;
btnDeactivate.IsEnabled = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让它真正等到装载,然后做东西,或设置延迟事件或某事,或者有人知道或理论可能会发生什么?
谢谢你的任何提示!
只需设置IsSynchronizedWithCurrentItem ="False".这将是解决它的最简单方法.
这里发生的是:在一切都被初始化之后(即在构造函数之后),Bindings将启动.此时将设置ListBox的ItemsSource.在此步骤中,一些ICollectionView魔术发生在幕后.实质上,ListBox将连接到源集合的默认CollectionView,其CurrentItem属性始终默认为第一个项目.现在,如果IsSynchronizedWithCurrentItem为true,则ListBox将更新SelectedItem以使其等于ICollectionView.CurrentItem.这就是导致你提到的问题的原因.
(注意:在所有这些发生之后,Loaded事件将被触发.因此,dnr3在Loaded事件中设置SelectedIndex = -1的注释也应该有效).
希望这是有道理的.