2013-04-27 56 views
0

我想要動態改變我的內容從一個AppBar蒙山驗證碼:ContentControl中不改變內容 - 函數從來沒有所謂

<Page.Resources> 
    <local:AppBarSelector x:Key="myAppBarSelector"/> 
</Page.Resources> 

<Page.BottomAppBar> 
    <AppBar> 
     <ContentControl Content="{Binding SelectedItem, ElementName=listBox}" ContentTemplateSelector="{StaticResource myAppBarSelector}"> 
      <ContentControl.Resources> 
       <DataTemplate x:Key="1"> 
        <TextBlock Text="Hallo Welt 1" Foreground="White" /> 
       </DataTemplate> 

       <DataTemplate x:Key="2"> 
        <TextBlock Text="Hallo Welt 2" Foreground="White" /> 
       </DataTemplate> 
      </ContentControl.Resources> 
     </ContentControl> 
    </AppBar> 
</Page.BottomAppBar> 

這是我的代碼背後:

public class AppBarSelector : DataTemplateSelector 
{ 
    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) 
    { 
     Debug.WriteLine((string)item); 
     if (item == null) return base.SelectTemplateCore(item, container); 

     var contentControl = (ContentControl)container; 
     var templateKey = (string)item; 

     return (DataTemplate)contentControl.Resources[templateKey]; 
    } 
} 

但這方法是神經調用。即使Debug.WriteLine函數。我的錯誤在哪裏?

+0

你確定你的物品實際上是一個字符串嗎?它可能是在這一點上除外。您的項目是您的綁定ItemsSource項目。 – NSGaga 2013-04-27 23:30:59

+0

是我填充ListView:'listBox.ItemsSource = new List {「1」,「2」,「3」,「4」};'我有第二個使用其他'Page.Resource'的ContentControl,但是也與列表視圖項的字符串 - 這很好,但這裏的功能不叫... – Cilenco 2013-04-28 08:34:49

+0

抱歉懷疑你:)你有任何錯誤在調試視圖?並再次微不足道,但你確定它不會'擊中'SelectTemplateCore(把一個斷點,而不僅僅是傾銷)。 – NSGaga 2013-04-28 19:05:20

回答

0

這裏只是一些意見後...
(注:這是一個有點普通,但我不能更具體的w/o更多的代碼,以反映的問題)

這應該工作「爲是' - 我沒有看到任何問題會產生這種情況(我檢查類似的例子很快,它與.ItemsSource = new List<string>{...}很好。

所以這不是罪魁禍首 - 但它不會傷害我建議 - 做一個適當的MVVM綁定到屬性,使列表ObservableCollection<> - 也總是建議有更多的higher-level對象(而不是隻有string)作爲你的項目(幫助在許多情況下與類似的問題綁定 - 該對象實現INotifyPropertyChanged等 - 並綁定到'屬性'那裏,而不是整個對象)。

另一個錯誤也提示了一些問題。

最後將兩個contentControls綁定在一起 - 通常你不需要這樣的事件。您可以直接使用樣式或XAML中的Triggers - 但大多數時候只是綁定到視圖模型中的屬性 - 並處理屬性「setter」中的「更改」。

你應該提出一個小小的引子,重複這個 - 誰知道這可能會幫助你意識到你做錯了什麼。

相關問題