简体   繁体   English

XAML绑定代码无法正常工作

[英]XAML binding code not working

I have small problem. 我有小问题。

Code behind: 代码背后:

...
public struct Project
{
    string Name;
    string Path;
    public Project(string Name, string Path = "")
    {
       this.Name = Name;
       this.Path = Path;
    }
}
...

Resources code: 资源代码:

<DataTemplate x:Key="ItemProjectTemplate">
        <StackPanel>
            <Image Source="Assets/project.png" Width="50" Height="50" />
            <TextBlock FontSize="22" Text="{Binding Name}" />
        </StackPanel>
</DataTemplate>

Normal code in Grid: 网格中的普通代码:

<ListView Grid.Column="1" HorizontalAlignment="Left" Height="511" 
     Margin="25,72,0,0" Grid.Row="1" VerticalAlignment="Top" Width="423"
     x:Name="Projects" ItemTemplate="{StaticResource ItemProjectTemplate}" />

I have no problem with ListView source, which is being set in C# code, and also my template is being loaded. 我对使用C#代码设置的ListView源没有任何问题,我的模板也正在加载。 But this happens when I'm running my application: 但是当我运行我的应用程序时会发生这种情况:

项目名称未显示

As you can see the project name (Project.Name ) is not being displayed, but in my ListView template is data binding, so it should work. 如您所见,项目名称(Project.Name )未显示,但在我的ListView模板中是数据绑定,因此它应该可以工作。 Does anybody know why is my data binding for a text not working? 有人知道为什么我的数据绑定文本不起作用? Please help. 请帮忙。

DataBinding works for Properties and not on Fields . DataBinding适用于Properties而不适用于Fields Replace Struct with class and make your fields as properties- 用类替换Struct并将字段设为属性 -

public class Project
{
    public string Name {get; set;}
    public string Path {get; set;}
    public Project(string Name, string Path = "")
    {
       this.Name = Name;
       this.Path = Path;
    }
}

You have to bind against public properties! 你必须绑定公共财产! And use classes instead of structs. 并使用类而不是结构。 Structs are passed by value to the GUI and hence, you can't make changes on the actual source-items. 结构按值传递给GUI,因此,您无法对实际的源项进行更改。

public class Project
{
    public string Name{ get; set;}
    public string Path{ get; set;}
    public Project(string Name, string Path = "")
    {
       this.Name = Name;
       this.Path = Path;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM