我是 wpf 的新手,我正在尝试使用 DataTemplate 创建菜单,以学习如何使用 DataTemplates。
我收到以下绑定错误,控件中没有出现任何文本,我不明白为什么。
绑定错误
System.Windows.Data Error: 40 : BindingExpression path error: 'DisplayName' property not found on 'object' ''StartOptionsViewModel' (HashCode=7730701)'. BindingExpression:Path=DisplayName; DataItem='StartOptionsViewModel' (HashCode=7730701); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
MainWindow.XAML 是:
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Colin's Test Application" Width="600" Height="400">
<Window.Resources>
<!-- WIZARD STEP TEMPLATE -->
<DataTemplate x:Key="OptionsTemplate">
<Border x:Name="bdOuter" BorderBrush="Black" BorderThickness="0,0,1,1" CornerRadius="12" Margin="1,1,1,12" Opacity="1" SnapsToDevicePixels="True" >
<Border x:Name="bdInner" Background="#FFFEFEFE" BorderBrush="Brown" BorderThickness="2,2,1,1" CornerRadius="12" Padding="2" >
<TextBlock x:Name="txt" Margin="4,0,0,0" Foreground="Black" Text="{Binding Path=DisplayName, Mode=OneWayToSource}" />
</Border>
</Border>
</DataTemplate>
</Window.Resources>
<StackPanel VerticalAlignment="Center">
<ItemsControl
ItemsSource="{Binding Path=StartOptions}"
ItemTemplate="{StaticResource OptionsTemplate}"
/>
</StackPanel>
</Window>
我的 MainWindoViewModel.cs
public partial class MainWindowViewModel
{
private List<StartOptionsViewModel> _listStartOptionsVM = new List<StartOptionsViewModel>();
public MainWindowViewModel()
{
_listStartOptionsVM.AddRange(new StartOptionsViewModel[]
{
new StartOptionsViewModel(new StartOption("New Application", StartOption.StartOptionTypes.Button)),
new StartOptionsViewModel(new StartOption("Exit Application", StartOption.StartOptionTypes.Button))
});
}
public ReadOnlyCollection<StartOptionsViewModel> StartOptions
{
get
{
return new ReadOnlyCollection<StartOptionsViewModel>(_listStartOptionsVM);
}
}
}
` StartOptionsViewModel.cs:
public class StartOptionsViewModel
{
private StartOption m_startOption = null;
public StartOptionsViewModel(StartOption p_startOption)
{
m_startOption = p_startOption;
}
#region Properties
public string DisplayName
{
get { return m_startOption.DisplayName; }
set
{
//...
}
}
#endregion
}