在我的应用中,我有一个保存/编辑页面。 当前流程如下:用户有一个主页面,其中包含元素列表。他可以点击“添加”按钮,进入“添加”页面,在该页面中,他可以输入信息并存储它。一旦他这样做,信息将被保存并显示在列表中。 如果他点击列表,他会转到“编辑”页面,在该页面中他可以更改信息。
实际上,Add和Edit页面是相同的,第二个填充了字段,而第一个没有。
我在这个页面中有3个列表框,一个用于严重性,一个用于类别,一个用于记者。在保存之前在列表框中选择此信息,并且在编辑阶段,应自动选择该信息,以便用户知道“旧”值。 为了自动选择值,我尝试了两种方法:
1 - 在我的xaml中:
<ListBox Height="103" Name="lbSeverities" Width="439" HorizontalAlignment="Left" Margin="20,0,0,0" SelectionMode="Single" ItemsSource="{Binding Severities}" DisplayMemberPath="Name" SelectedItem="{Binding Task.Severity}"/>
我还将严重级别的Equals方法覆盖为合理的实现。
2-在我的xaml
<ListBox Height="103" Name="lbSeverities" Width="439" HorizontalAlignment="Left" Margin="20,0,0,0" SelectionMode="Single" ItemsSource="{Binding Severities}" DisplayMemberPath="Name" SelectedIndex="{Binding Task.Severity, Converter={StaticResource SeverityToIndexConverter}}"/>
我使用以下代码创建了SeverityToIndexConverter:
public class SeverityToIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value is Severity)
{
Severity currentSeverity = (Severity)value;
for (int i = 0; i < (App.Current as App).MainViewModel.Severities.Count; i++)
{
Severity sev = (App.Current as App).MainViewModel.Severities[i];
if (currentSeverity.ID == sev.ID)
return i;
}
}
return -1;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
它们都呈现相同的结果:有时会自动选择值,但有时不会。选择时非常不稳定。 我想到了一些异常,试图抓住它,但我什么也得不到。 我也尝试调试,我注意到在情况1中,对于集合的所有成员并行调用equals方法,所以我尝试了第二种方法。调试并没有让我得到任何答案。
有没有人遇到类似的情况? 当用户进入“编辑”页面时,我该怎么做才能选择列表框值?
谢谢, 奥斯卡
答案 0 :(得分:1)
我做同样的事情。我的xaml看起来就像是你的第一个例子。
这就是我要做的事情:
创建一个名为Severity的新属性。在getter中返回Task.Severity。将列表框SelectedItem绑定到新属性。
这可能也是一个时间问题,因此一旦列表框加载了列表,您可能必须在新属性上调用NotifyPropertyChanged。