我想以编程方式更改 FlipView 的 SelectedIndex。我的 ViewModel 看起来像这样:
public class MyViewModel : ViewModelBase {
private int _flipViewIndex;
public int FlipViewIndex
{
get { return _flipViewIndex; }
private set { Set(ref _flipViewIndex, value); }
}
private string _logText;
public string LogText
{
get { return _logText; }
private set { Set(ref _logText, value); }
}
public async void Log(string text)
{
CoreDispatcher dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcher.HasThreadAccess)
{
LogText += text + "\n";
}
else
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Log(text));
}
}
public async void SetIndex(int index)
{
CoreDispatcher dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcher.HasThreadAccess)
{
FlipViewIndex = index;
}
else
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => SetIndex(index));
}
}
}
Set()
提高INotifyPropertyChanged.PropertyChanged()
。
我的 XAML 看起来像这样:
<views:BaseView>
<Grid DataContext="{StaticResource ViewModel}">
<FlipView SelectedIndex="{Binding FlipViewIndex}">
<Control1 />
<Control2 />
<Control3 />
</FlipView>
<TextBlock Text="{Binding LogText}" />
</Grid>
</views.BaseView>
View 和 ViewModel 似乎绑定正确。当我ViewModel.Log("foo")
从控制器调用时,TextBlock 的文本会更新以反映更改。
问题是,当我调用时ViewModel.SetIndex(n)
,FlipViewSelectedIndex
没有更新到n
,它只是保持在 0。任何想法为什么会发生这种情况?