2013-12-19 207 views
0
<UserControl 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
x:Class="Menupedia.MiniRestaurantViewer" 
x:Name="UserControl" Width="80" Height="100"> 

<Grid x:Name="LayoutRoot"> 
    <Label x:Name="label_Name" Content="{Binding _name, Mode=OneWay}" HorizontalAlignment="Stretch" Width="80" FontFamily="Public Enemy NF" FontSize="14.667" Foreground="#FFEF7B54" Margin="0" Height="20" VerticalAlignment="Bottom"/> 
    <Image x:Name="image_Logo" Source="{Binding _logo, Mode=OneWay}" HorizontalAlignment="Left" Width="80" Height="80" VerticalAlignment="Top"/> 
    <Border BorderBrush="#FFF15A28" BorderThickness="1" Height="80" CornerRadius="2" VerticalAlignment="Top" Width="80" HorizontalAlignment="Left"/> 
</Grid> 

WPF自定义控件不绑定

public partial class MiniRestaurantViewer : UserControl 
{ 
    public int _id {get{return id;}} 
    public string _name {get{return name;}} 
    public ImageSource _logo {get{return logo;}} 

    public MiniRestaurantViewer(int id, string name,byte[] logo) 
    { 
     this.id = id; 
     this.name = name; 
     this.logo = ByteArrayToImageSource(logo); 
     this.InitializeComponent(); 
    } 

    private int id; 
    private string name; 
    private ImageSource logo; 

    private ImageSource ByteArrayToImageSource(byte[] data) 
    { 
     BitmapImage image = null; 
     if (null != data) 
     { 
      image = new BitmapImage(); 
      image.BeginInit(); 
      image.StreamSource = new System.IO.MemoryStream(data); 
      image.EndInit(); 
     } 
     return image; 
    } 

    public MiniRestaurantViewer() 
    { 
     this.InitializeComponent(); 
    } 
} 

这是我的自定义控制。我想这样做

ListBox.Items.Add(new MiniRestaurantViewer(1,"test",null)); 

当我这样做,我看到的UI元素,但它是空的(绑定不起作用)。通过手表,虽然我发现公共财产有价值..我不知道如何使它的工作,我一直试着从3天请帮助我。 :(

回答

2

您需要设置DataContext to itself如果属性在于后面的代码

<UserControl x:Class="Menupedia.MiniRestaurantViewer" 
      x:Name="UserControl" Width="80" Height="100" 
      DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
+1

生病给它一个镜头谢谢 –

+0

您的欢迎AymanSalah .. :) –

2

你可以做到这一点this.DataContext = this;,使你的代码的作品,但你是远远离这意味着使用MVVM尝试读取this第一,因为它可以是一个良好的开端,一个begineer

WPF的最佳实践
public MiniRestaurantViewer(int id, string name,byte[] logo) 
    { 
     this.id = id; 
     this.name = name; 
     this.logo = ByteArrayToImageSource(logo); 
     this.InitializeComponent(); 
     this.DataContext = this; 

    } 
+0

非常感谢我知道我远离良好的代码。但即时通讯新的wpf和我有一个项目由于下一个星期一,我必须使它的工作,我选择使用WPF而不是Windows窗体,所以即时通讯学习一起开发这个程序。生病阅读你的链接 –

1

首先,我认为你需要使用双向绑定,能够作出改变两者的方式 - 从您的视图模型并从模型中查看id在你的控件列表框中看不到,所以可能是你的mainWindow。在这种情况下,你有两个oportunities - 或者设置mainWindow的datacontext,就像在下面的答案中一样,或者设置ListBox.Datacontext。希望这会帮助你。