0

我是 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
}
4

1 回答 1

0

首先,你以错误的方式绑定你的文本块模式,因为文本框文本永远不会从 ui 设置,这意味着用户儿子在运行时它的 smode 不能是 onewaytosource 它应该是一种方式,所以首先你应该像这样正确..

 <TextBlock
    x:Name="txt"
    Margin="4,0,0,0"
    Foreground="Black"
    Text="{Binding Path=DisplayName, Mode=OneWay}"
    />

如果您的问题仍然存在,请首先使其正确并运行您的代码并发表评论。

于 2013-07-12T08:49:45.500 回答