在WPF中的代码隐藏中为ListBox创建ItemTemplate - 第二部分

时间:2014-04-15 10:41:07

标签: c# wpf listbox itemtemplate

我将这个问题命名为第二部分,因为我已经问过一个类似但更简单的问题,就是在这里为Create ItemTemplate for ListBox in code-beind in WPF

在WPF中为ListBox创建一个ItemTemplat

现在我要扩展我的问题。我想为ListBox创建一个ItemTemplate,以便可以使用或不使用ObservableCollection绑定。

如果我不想将ItemsSource绑定到ObservableCollection,请使用以下代码:

var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);

var template = new DataTemplate();            
template.VisualTree = textBlockFactory;

MyListBox.ItemTemplate = template;

但是,对于绑定到ObservableCollection的ItemsSource,它不起作用,因为TextBlock.TextProperty必须绑定到DisplayMemberPath属性。

抱歉语法不好。

1 个答案:

答案 0 :(得分:3)

首先,您需要创建一个确定状态的变量:使用集合,或者仅使用字符串数组。这个标志也可以是依赖属性,在我的例子中它是SomeFlag

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    bool SomeFlag = false;

    if (SomeFlag == false)
    {
        var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
        textBlockFactory.SetValue(TextBlock.TextProperty, new Binding("."));

        textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
        textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
        textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);

        var template = new DataTemplate();
        template.VisualTree = textBlockFactory;

        MyListBox.ItemTemplate = template;
    }
    else
    {
        MyListBox.DisplayMemberPath = "Name";
        MyListBox.SelectedValuePath = "Age";
    }
}

要进行测试,请添加SelectionChanged事件的处理程序:

private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("SelectedValue is " + MyListBox.SelectedValue);
}

以下是一个完整的例子:

XAML

<Grid>
    <ListBox Name="MyListBox"
             SelectionChanged="MyListBox_SelectionChanged"
             ItemsSource="{Binding Path=MyCollection}" />
</Grid>

Code-behind

public partial class MainWindow : Window
{
    ViewModel MyViewModel = new ViewModel();

    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = MyViewModel;

        MyViewModel.MyCollection = new ObservableCollection<Person>();

        MyViewModel.MyCollection.Add(new Person()
        {
            Age = 22,
            Name = "Nick",
        });

        MyViewModel.MyCollection.Add(new Person()
        {
            Age = 11,
            Name = "Sam",
        });

        MyViewModel.MyCollection.Add(new Person()
        {
            Name = "Kate",
            Age = 15,
        });
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        bool SomeFlag = false;

        if (SomeFlag == false)
        {
            var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
            textBlockFactory.SetValue(TextBlock.TextProperty, new Binding("."));

            textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
            textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
            textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);

            var template = new DataTemplate();
            template.VisualTree = textBlockFactory;

            MyListBox.ItemTemplate = template;
        }
        else
        {
            MyListBox.DisplayMemberPath = "Name";
            MyListBox.SelectedValuePath = "Age";
        }
    }

    private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("SelectedValue is " + MyListBox.SelectedValue);
    }
}

public class ViewModel : NotificationObject
{
    #region MyCollection

    public ObservableCollection<Person> MyCollection
    {
        get;
        set;
    }

    #endregion
}

#region Model

public class Person
{
    public string Name
    {
        get;
        set;
    }

    public int Age
    {
        get;
        set;
    }
}

#endregion

#region NotificationObject

public class NotificationObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

#endregion