2010-10-30 49 views
0

我有一個列表框它有它的ViewModel - 我們稱之爲ListBoxViewModel。列表框中有ItemsSource="{Binding MyItems}"屬性,對應於ObservableCollection<MyItemType>ListBoxViewModel列表框有其項目模板它創建MyItemControl控件在列表框。問題是,我期望MyItemControl具有MyItemType實例爲DataContext。但是DataContext爲空。什麼是最好的實施?ListBox ItemTempate DataContext

回答

0

我剛錯誤的語法地方。正確的解決方案的例子是:

的App.xaml

<Application x:Class="WpfProblem2.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:WpfProblem2" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
     <DataTemplate x:Key="myTemplate"> 
      <local:MyItemControl/> 
     </DataTemplate> 
    </Application.Resources> 
</Application> 

ListBoxViewModel.cs

namespace WpfProblem2 { 
    public class ListBoxViewModel : DependencyObject { 

     public ListBoxViewModel() { 
      MyItems = new ObservableCollection<MyItemType>() { 
       new MyItemType() { TextValue = "A" }, 
       new MyItemType() { TextValue = "B" }, 
       new MyItemType() { TextValue = "C" }, 
       new MyItemType() { TextValue = "D" } 
      }; 
     } 

     public ObservableCollection<MyItemType> MyItems { get; private set; } 
    } 
} 

MainWindow.xaml

<Window x:Class="WpfProblem2.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> 
    <ListBox x:Name="listBox" ItemTemplate="{StaticResource myTemplate}" ItemsSource="{Binding MyItems}" /> 
</Window> 

MainWindow.xaml.cs

namespace WpfProblem2 { 
    public partial class MainWindow : Window { 
     public MainWindow() { 
      InitializeComponent(); 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) { 
      listBox.DataContext = new ListBoxViewModel(); 
     } 
    } 
} 

MyItemControl.xaml

<UserControl x:Class="WpfProblem2.MyItemControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="50" d:DesignWidth="300"> 
    <TextBox Text="{Binding TextValue}" /> 
</UserControl> 

MyItemType.cs

namespace WpfProblem2 { 
    public class MyItemType : DependencyObject { 

     public static readonly DependencyProperty TextValueProperty = DependencyProperty.Register("TextValue", typeof(string), typeof(MyItemType)); 
     public string TextValue { 
      get { return (string)GetValue(TextValueProperty); } 
      set { SetValue(TextValueProperty, value); } 
     } 

    } 
} 
相關問題