[英]C# UWP binding splitview IsPaneOpen to viewmodel
遇到此問題時,我正在學習通用Windows應用程序上的一些知識:我想構建一個帶有漢堡按鈕的splitview菜單,而無需編寫代碼。 所以我設置了一個帶屬性的viewmodel和一個用於更改該屬性值的命令。 為了檢查命令是否被解雇,我提供了一條小消息對話框。 我將splitview IsPaneOpen綁定到了我的viewmodel,但是以某種方式似乎不起作用。
XAML代碼
<Page.Resources>
<vm:PaneViewModel x:Key="viewModel"/>
</Page.Resources>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource viewModel}" >
<Button Content="Test" Command="{Binding Path=OpenPane, Mode=TwoWay}" ManipulationMode="All"/>
<SplitView DisplayMode="CompactInline"
x:Name="Splitview"
OpenPaneLength="150"
CompactPaneLength="20"
IsPaneOpen="{Binding IsPaneOpen, Mode=TwoWay}">
<SplitView.Pane>
<StackPanel Height="400">
<Button Height="40">
<TextBlock Text="Testbutton" Width="100"/>
</Button>
</StackPanel>
</SplitView.Pane>
<SplitView.Content>
<TextBlock Margin="30" Text="{Binding ShowAnything, Mode=TwoWay}"/>
</SplitView.Content>
</SplitView>
</StackPanel>
ViewModel代碼
internal class PaneViewModel
{
public PaneViewModel()
{
OpenPane = new OpenPaneCommand(this);
}
private bool isPaneOpen = true;
public bool IsPaneOpen
{
get
{
return isPaneOpen;
}
set
{
isPaneOpen = value;
}
}
public string ShowAnything { get { return isPaneOpen.ToString(); } }
public OpenPaneCommand OpenPane { get; set; }
public void OpenPaneMethod()
{
if (isPaneOpen == false)
isPaneOpen = true;
else
isPaneOpen = false;
}
}
和命令代碼
internal class OpenPaneCommand : ICommand
{
public OpenPaneCommand(PaneViewModel ViewModel)
{
this.viewModel = ViewModel;
}
private PaneViewModel viewModel;
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Blub();
viewModel.OpenPaneMethod();
}
async private void Blub()
{
var dialog = new MessageDialog("Testausgabe");
await dialog.ShowAsync();
}
就像我說的-消息對話框出現了,但是splitview.content或ispaneopen中的文本塊似乎都沒有改變。 調試告訴我,我更改值的方法的確確實會更改值。 所以我想知道我的綁定或數據上下文設置是否已關閉。
也許你們對我有暗示,我的誤會來自哪里。
謝謝!
梅克
您的綁定無法正常工作,因為沒有通知您ViewModel的更改。 您的VM需要實現INotifyPropertyChanged
接口,並在屬性更改時引發PropertyChanged事件。
因此,通常您會將這樣的內容放入設置器中:
...
set
{
isPaneOpen = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsPaneOpen");
}
...
我認為您的視圖模型應該繼承ObservableObject
。 並進一步更新所有屬性,如下所示:
public bool IsPaneOpen
{
get { return isPaneOpen; }
set
{
this.Set<bool>(ref this._loisPaneOpendedPendingCount, value);
}
}
與ShowAnything
屬性相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.