在WP8中,他们忘了将SelectedItem作为依赖属性提供,因此我无法绑定它。我用它来修复:http://dotnet-redzone.blogspot.com/2012/11/windows-phone-8longlistselector.html
这样做,我注意到我无法从ViewModel重置属性,即如果我在ViewModel中将项目设置为null,则不会影响UI。我已经在UI中提供了双向绑定,但仍然在ViewModel中将项设置为null不会更改LongListSelector中的选定项。我也不想使用SelectionChanged事件,因为我在WP7.5应用程序和WP8应用程序之间共享ViewModel,因此我想尽可能多地推送到ViewModel中。有解决方案吗?
答案 0 :(得分:11)
您正在使用的自定义LongListSelector类似乎无法正确处理setter。
使用以下内容替换OnSelectedItemChanged回调:
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var selector = (LongListSelector)d;
selector.SetSelectedItem(e);
}
private void SetSelectedItem(DependencyPropertyChangedEventArgs e)
{
base.SelectedItem = e.NewValue;
}
答案 1 :(得分:2)
这两部分有完整版本:
public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
{
public LongListSelector()
{
SelectionChanged += LongListSelector_SelectionChanged;
}
void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItem = base.SelectedItem;
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register(
"SelectedItem",
typeof(object),
typeof(LongListSelector),
new PropertyMetadata(null, OnSelectedItemChanged)
);
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var selector = (LongListSelector)d;
selector.SetSelectedItem(e);
}
private void SetSelectedItem(DependencyPropertyChangedEventArgs e)
{
base.SelectedItem = e.NewValue;
}
public new object SelectedItem
{
get { return GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
}