如何将类字段绑定到自定义模板中的元素? (WPF)

时间:2019-03-07 22:31:52

标签: c# wpf binding

如何将类字段绑定到自定义ListBoxItem模板中的元素? 此示例代码缺少类定义,ListBox名称等某些方面,我只是在绑定过程中苦苦挣扎。

<ListBox>
    <ListBox.Resources>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>

                       <!-- how to bind class fields to these elements -->

                        <StackPanel Orientation="Horizontal">
                            <Label></Label>
                            <Image></Image>
                        </StackPanel>

                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>

    <!-- adding items dynamically -->

</ListBox>

C#代码应类似于:

ListBoxItem listBoxItem = new ListBoxItem();
listBoxItem.Content = new MyClass(){ Name="MyName", Image="ImagePath"}
... append to ListBox ... 

2 个答案:

答案 0 :(得分:1)

在WPF中进行开发时,鼓励MvvM促进关注点分离。为此,可以实现一个带有属性的视图模型,然后将其绑定到视图。当您希望UI(视图)了解视图模型提供的数据更改时,必须实现INotifyPropertyChanged接口,如下所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;    

namespace ViewModels
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public BaseViewModel()
        {
             //ctor
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            UIThread( () =>
            {
                //make sure the event is raised on the main thread
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            });
        }

        Dispatcher _dispacther;

        protected void UIThread(Action action)
        {
            if (_dispacther == null)
            {
                _dispacther = Dispatcher.CurrentDispatcher;
            }
            _dispacther.Invoke(action);
        }
    }
}  

您的Hello类将从BaseViewModel派生并提供OnPropertyChanged();。在这样的属性中:

    private string name;

    public string Name
    {
        get { return name; }
        set { name= value; OnPropertyChanged(); }
    }

现在,当您在列表框中更改所选项目的名称时,它将反映在UI中。尝试一下! 此实现确保事件在主线程上引发,因此在调用事件时不需要这样做。另外,[CallerMemberName]会填充您调用的属性的名称!

答案 1 :(得分:0)

弄清楚了。 C#类:

        public class Hello
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string ImagePath { get; set; }
    }

C#动态添加:

ListBoxItem lbi = new ListBoxItem();
lbi.Content = new Hello() { Name = "hello man", Description="I am superman.", ImagePath="Images/myimage.png"};
menu.Items.Add(lbi);

XAML:

            <ListBox Name="menu" ItemsSource="{Binding}">

                <ListBox.Resources>

                    <Style TargetType="ListBoxItem">
                        <Setter Property="ContentTemplate">
                            <Setter.Value>

                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <Label FontWeight="Bold" Content="{Binding Name}"></Label>
                                        <Label Content="{Binding Description}"></Label>
                                        <Image Source="{Binding ImagePath}" Width="30" Height="30"></Image>
                                    </StackPanel>

                                </DataTemplate>

                            </Setter.Value>
                        </Setter>
                    </Style>
                </ListBox.Resources>


            </ListBox>