如何取消設置應用於對象的綁定,以便我可以從另一個位置對其應用另一個綁定?WPF中的未設置/更改綁定
假設我有兩個數據模板綁定到相同的對象引用。
數據模板#1是要加載的默認模板。我試圖將一個按鈕命令將Function1
從我的DataContext類綁定:
<Button Content="Button 1" CommandParameter="{Binding }" Command="{Binding DataContext.Function1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
這實際工作和功能被綁定。但是,當我嘗試加載數據模板#2相同的對象(而試圖另一個按鈕命令綁定到從我的DataContext類不同的功能(Function2
)):
<Button Content="Button 2" CommandParameter="{Binding }" Command="{Binding DataContext.Function2, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
它不工作和第一個綁定仍然是執行的綁定。有沒有解決這個問題的方法? (爲了更好的問題上下文)
編輯:
我定義我的模板在我Window.Resources:
<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<local:View1 />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<local:View2 />
</DataTemplate>
</Window.Resources>
的View1.xaml和View2.xaml包含按鈕定義,我如上所述(我希望他們能夠控制我的流程)。 ViewModel1和ViewModel2是我的ViewModel,它實現了接口IPageViewModel
,它是我的變量CurrentPageViewModel
的類型。
在我的XAML,我綁定ContentControl
給變量CurrentPageViewModel
:
<ContentControl Content="{Binding CurrentPageViewModel}" HorizontalAlignment="Center"/>
在我.CS,我有一個列表定義爲List<IPageViewModel> PageViewModels
,我用它來遏制我的兩個視圖模型的實例:
PageViewModels.Add(new ViewModel1());
PageViewModels.Add(new ViewModel2());
// Set starting page
CurrentPageViewModel = PageViewModels[0];
當我試圖將我的CurrentPageViewModel
更改爲其他視圖模型時,這是我希望新綁定起作用的時候。不幸的是,事實並非如此。我是否正確地做事情?
這些按鈕是DataTemplate的一部分嗎?你如何設置DataTemplate?按名字?隱?有什麼條件適用於何時使用哪種功能?你不能只使用2個不同的模板? – dowhilefor
你如何在DataTempates之間切換?根據不同的情況,你可以調用[CommandManager.InvalidateRequerySuggested](http://msdn.microsoft.com/en-us/library/system.windows.input.commandmanager.invalidaterequerysuggested.aspx)來更新綁定。 – keyboardP
@keyboardP InvalidateRequerySuggested不更新綁定,它只是告訴命令系統「再次檢查命令是否可以執行」它只是重新評估CanExecute命令。 – dowhilefor