在WPF中如何在代码中更改DataTemplate中TextBlock的文本绑定?

4

我有一个ListBox,其ItemsSource绑定到对象列表。ListBox具有一个ItemTemplate,其中包含一个TextBlock的DataTemplate。TextBlock的Text绑定到对象的Name属性(即Text =“{Binding Name}”)。

我想提供一个单选按钮来显示相同列表的不同视图。例如,允许用户在名称属性和ID属性之间切换。

我在2381740中找到了一个SO答案,但我还设置了边框和文本框样式的数据模板(请参见下面的代码)。

是否有任何方法只重置Textblock绑定?我不想重新创建整个datatemplate。实际上,我甚至不确定如何做到这一点,是否有将xaml转换为代码的简单方法?

谢谢 Cody

<DataTemplate>
  <Border Margin="0 0 2 2"
          BorderBrush="Black"
          BorderThickness="3"
          CornerRadius="4"
          Padding="3">
      <TextBlock Style="{StaticResource listBoxItemStyle}"
                 Text="{Binding Name}" />
  </Border>
</DataTemplate>
3个回答

14

Wallstreet Programmer的解决方案对你很有效,因为你在使用单选按钮。但是我认为应该提供一种更通用的解决方案,以便未来阅读此问题的读者也可以受益。

你可以将你的DataTemplate更改为使用普通的"{Binding}"

<DataTemplate x:Key="ItemDisplayTemplate">
  <Border ...> 
    <TextBlock ...
               Text="{Binding}" /> 
  </Border> 
</DataTemplate> 

在代码中,您不必重新创建完整的DataTemplate。您只需要重新创建这个:

<DataTemplate>
  <ContentPresenter Content="{Binding Name}" ContentTemplate="{StaticResource ItemDisplayTemplate}" />
</DataTemplate>

这很容易:

private DataTemplate GeneratePropertyBoundTemplate(string property, string templateKey)
{
  var template = FindResource(templateKey);
  FrameworkElementFactory factory = new FrameworkElementFactory(typeof(ContentPresenter)); 
  factory.SetValue(ContentPresenter.ContentTemplateProperty, template);
  factory.SetBinding(ContentPresenter.ContentProperty, new Binding(property)); 
  return new DataTemplate { VisualTree = factory }; 
} 

如果你有许多属性,即使在你的单选按钮示例中,这会非常方便。


8

请简单处理,使用两个文本块并隐藏其中一个。

XAML:

<Window x:Class="Test.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="300" Width="300">

  <Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
  </Window.Resources>

  <StackPanel>
    <RadioButton Name="nameRadioBtn" Content="Name" IsChecked="True"/>
    <RadioButton Name="lengthRadioBtn" Content="Length" />
    <ListBox
      ItemsSource="{Binding Path=Items}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Border BorderBrush="Red" BorderThickness="1">
            <Grid>
              <TextBlock 
                Text="{Binding .}" 
                Visibility="{Binding Path=IsChecked, ElementName=nameRadioBtn, 
                  Converter={StaticResource BooleanToVisibilityConverter}}" />
              <TextBlock 
                Text="{Binding Path=Length}" 
                Visibility="{Binding Path=IsChecked, ElementName=lengthRadioBtn,
                  Converter={StaticResource BooleanToVisibilityConverter}}" />
            </Grid>
          </Border>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  </StackPanel>        
</Window>

代码后台:

using System.Collections.Generic;
using System.Windows;

namespace Test
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            DataContext = this;
        }

        public IEnumerable<string> Items
        {
            get
            {
                return new List<string>() {"Bob", "Sally", "Anna"};
            }
        }
    }
}

这是一个更好的解决方案,特别是因为它支持同时显示两个。谢谢! - code
1
是的,考虑到需要将两个值绑定到单选按钮,这是一个非常好的解决方案。 (+1) 您可能还对我添加的更通用的解决方案感兴趣。 - Ray Burns

1

您也可以使用值转换器来选择数据对象的任何属性。您需要绑定到整个对象而不是单个属性。如果您的数据对象实现了INotifyPropertyChanged,则此解决方案将无法正常工作。

XAML

<Window x:Class="Test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Test="clr-namespace:Test"
    Height="300" Width="300">

    <Window.Resources>
        <Test:PropertyPickerConverter x:Key="PropertyPickerConverter" />
    </Window.Resources>

    <StackPanel>
        <RadioButton Content="Name" Click="OnRadioButtonClick" IsChecked="True"/>
        <RadioButton Content="Length" Click="OnRadioButtonClick" />
        <ListBox
            ItemsSource="{Binding Path=Items}"
            Name="_listBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderBrush="Red" BorderThickness="1">
                        <StackPanel>
                            <TextBlock 
                                Text="{Binding ., Converter={StaticResource PropertyPickerConverter}}" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>

</Window>

代码后端:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Test
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            _propertyPickerConverter = FindResource("PropertyPickerConverter") as PropertyPickerConverter;
            _propertyPickerConverter.PropertyName = "Name";

            DataContext = this;
        }

        public IEnumerable<string> Items
        {
            get
            {
                return new List<string>() {"Bob", "Sally", "Anna"};
            }
        }

        private void OnRadioButtonClick(object sender, RoutedEventArgs e)
        {
            _propertyPickerConverter.PropertyName = (sender as RadioButton).Content as string;

            _listBox.Items.Refresh();
        }

        private PropertyPickerConverter _propertyPickerConverter;
    }

    public class PropertyPickerConverter : IValueConverter
    {
        public string PropertyName { get; set; }

        #region IValueConverter Members
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string item = value as string;
            switch (PropertyName)
            {
                case "Name": return item;
                case "Length": return item.Length;
                default: return null;
            }
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
        #endregion
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接