2013-07-01 26 views
2

如何取消設置應用於對象的綁定,以便我可以從另一個位置對其應用另一個綁定?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更改爲其他視圖模型時,這是我希望新綁定起作用的時候。不幸的是,事實並非如此。我是否正確地做事情?

+2

這些按鈕是DataTemplate的一部分嗎?你如何設置DataTemplate?按名字?隱?有什麼條件適用於何時使用哪種功能?你不能只使用2個不同的模板? – dowhilefor

+0

你如何在DataTempates之間切換?根據不同的情況,你可以調用[CommandManager.InvalidateRequerySuggested](http://msdn.microsoft.com/en-us/library/system.windows.input.commandmanager.invalidaterequerysuggested.aspx)來更新綁定。 – keyboardP

+0

@keyboardP InvalidateRequerySuggested不更新綁定,它只是告訴命令系統「再次檢查命令是否可以執行」它只是重新評估CanExecute命令。 – dowhilefor

回答

1

如果由於某種原因,您無法使用兩個不同的DataTemplates,通常是因爲數據模型非常大或複雜,我建議使用ContentControlDataTemplateSelector

在您的DataTemplates中放置另一個ContentControl,創建2個包含您的按鈕的DataTemplates,其中一個帶有Function1和Function2。創建一個DataTemplateSelector並將其設置在最初的ContentControl上。 DataTemplateSelector現在只需要根據決定選擇適當的模板,例如項目的類型或項目上的屬性等。

1

如果您仍然想要取消設置綁定,可以使用以下代碼: BindingOperations.ClearBinding(txtName, TextBox.TextProperty)

但是TemplateSelector方法會更高效。

+0

我實際上已經嘗試過這個解決方案,但是如何將我的對象參數轉換爲System.Window.DependencyObject?我嘗試鑄造,但它不起作用。 – captcalamares