I have a ListBox which has its ViewModel - let's call it ListBoxViewModel. List box has ItemsSource="{Binding MyItems}"
attribute which corresponds to ObservableCollection<MyItemType>
in ListBoxViewModel. ListBox has its ItemTem开发者_Python百科plate which creates MyItemControl controls in ListBox. The question is that I expect that MyItemControl has MyItemType instance as DataContext. But DataContext is null. What is the best implementation?
Set the data context explictly
I had just wrong syntax somewhere. Correct solution example is:
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); }
}
}
}
精彩评论