WPF自定义控件不绑定

时间:2013-12-19 09:57:30

标签: c# wpf user-controls bind

<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>

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天,请帮助我。 :(

3 个答案:

答案 0 :(得分:2)

您可以执行此操作this.DataContext = this;以使您的代码正常工作,但您远离wpf的最佳实践,这意味着使用MVVM首先尝试阅读this,因为它可能是一个良好的开端一个乞丐

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

    }

答案 1 :(得分:2)

如果属性位于代码后面,则需要设置DataContext to itself

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

答案 2 :(得分:1)

首先,我认为您需要使用双向绑定才能双向进行更改 - 从视图到模型以及从模型到视图。我没有在你的控制列表框中看到,所以可能是你的mainWindow。在这种情况下,你有两个机会 - 或者设置mainWindow的datacontext,如下面的答案,或设置ListBox.Datacontext。希望这会对你有所帮助。