我有一个 ListBox ,它有ViewModel - 我们称之为 ListBoxViewModel 。列表框具有ItemsSource="{Binding MyItems}"
属性,该属性对应于 ListBoxViewModel 中的ObservableCollection<MyItemType>
。 ListBox 有 ItemTemplate ,可在 ListBox 中创建 MyItemControl 控件。问题是我希望 MyItemControl 将 MyItemType 实例作为 DataContext 。但 DataContext 为空。什么是最佳实施?
答案 0 :(得分:0)
明确设置datacontext
答案 1 :(得分: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); }
}
}
}