2012-10-27 198 views
0

我有一个小问题。背后XAML绑定代码不起作用

代码:

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

资源代码:网格

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

普通代码:

<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}" /> 

我有ListView的来源,这是在C#中被设置没问题代码,还有我的模板正在加载。但是,出现这种情况时,我跑我的应用程序:

Project name is not being displayed

正如你可以看到未显示的项目名称(Project.Name),但在我的ListView模板数据绑定,所以它应该工作。有人知道为什么我的数据绑定文本不工作?请帮忙。

+0

这不可能是WPF和地铁。 – mydogisbox

+0

我想到的第一件事:你有没有适当地设置ItemsSource?如果没有Datacontext,绑定将失败。 –

回答

1

DataBinding适用于Properties而不适用于Fields。将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; 
    } 
} 
1

您必须对公共属性进行绑定!并使用类而不是结构。结构按值传递给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; 
    } 
} 
相关问题