【问题标题】:WPF binding with ContentControl not working与 ContentControl 的 WPF 绑定不起作用
【发布时间】:2013-08-22 23:25:00
【问题描述】:

我刚开始使用 WPF,但我的绑定不起作用。
当我启动应用程序时,屏幕只是空白。

这是我的 XAML

<Window x:Class="HelloWPF.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">
<Grid>
    <ContentControl Content="{Binding PersonOne}" Width="auto" Height="auto" >
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding FirstName}" FontSize="15" />
                    <TextBlock Text="{Binding Age}" FontSize="12" />
                </StackPanel>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
</Grid>

这是代码:

public partial class MainWindow : Window
{
    public Person PersonOne;
    public MainWindow()
    {
        InitializeComponent();

        PersonOne = new Person();
        PersonOne.Gender = Gender.Female;
        PersonOne.Age = 24;
        PersonOne.FirstName = "Jane";
        PersonOne.LastName = "Joe";

        this.DataContext = this;
    }
}

这是person类

public class Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }

    public int Age { get; set; }
    public Gender Gender { get; set; }
}

public enum Gender
{
    Male, 
    Female
}

我做错了什么?

【问题讨论】:

    标签: wpf contentcontrol


    【解决方案1】:

    你不能绑定到字段,只能绑定属性,所以改变这个:

    public Person PersonOne;
    

    到这里:

    public Person PersonOne {get;set;}
    

    顺便说一句,您可能需要创建一个 ViewModel 而不是将数据放入 Window 本身。

    【讨论】:

    • 我也会将其设为 DependencyProperty,以便您可以挂钩属性更改...
    • @Nick 不同意。 OP 需要创建一个合适的 ViewModel。对真正属于 ViewModel 的数据使用 DependencyProperties 是有史以来最糟糕的想法。
    • 称其为“有史以来最糟糕的想法”有点苛刻......并非一切都需要成熟的 MVVM 结构。
    • 谢谢,现在可以使用了。我会看看 ViewModel 和 DependencyProperties,我刚开始使用 WPF,所以我对这些一无所知。
    猜你喜欢
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2016-09-27
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多