如何绑定listView中项的子属性?

问题描述 投票:0回答:2

我试图将属性绑定到另一个属性时遇到困难。这两个属性是:

  • 在richTextBox中,'Content'依赖项属性
  • 在listView中,selectedItem是Book,所选书籍具有名为“End”的字符串属性。

我必须使用2个转换器将Content转换为字符串,将字符串转换为Content,因此我无法使用TwoWay绑定模式。

使用此代码:

<controls:RichEditControl
    x:Name="richEditControl1"
    BarManager="{Binding ElementName=barManager1, Mode=OneTime}"
    HorizontalRulerVisibility="Collapsed"
    VerticalRulerVisibility="Collapsed"
    Content="{Binding ElementName=listBoxBooks, Path=SelectedItem.End, Converter={StaticResource PlainContentConverter}, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"/>

应该有一半的绑定,但我无法弄清楚如何实现下半部分,我的意思是从listView - >(Book)selectedItem - > End到Content属性。

我试过这样的事情:

Binding myBinding = new Binding("Content");
myBinding.Source = richEditControl1;
myBinding.Mode = BindingMode.OneWay;
listBoxBooks.SetBinding(ListView.SelectedItemProperty, myBinding);

但这是错误的,因为我不想绑定整个SelectedItemProperty但只想绑定它的'End'属性。 (selectedItem是一个'Book'类)。

谢谢。

EDIT1我根据评论中给出的建议改变了代码隐藏,但没有任何成功。代码是:

Binding myBinding = new Binding("End");
myBinding.Source = (Book)listBoxBooks.SelectedItem;
myBinding.Mode = BindingMode.OneWay;
richEditControl1.SetBinding(RichEditControl.ContentProperty, myBinding);

(实际上它反转了绑定的方向,但我认为第一个方向是错误的)。

c# .net wpf data-binding 2-way-object-databinding
2个回答
0
投票

谢谢你的回答,但我刚刚找到了一个解决方案:事实上,我并没有告诉你我尝试使用等于TwoWay的绑定模式,我告诉过你这是不可能的。但我错了,TwoWay与转换器兼容,因为转换器包含两种方法用于每个转换方向。有可能,使用此代码:

Content="{Binding ElementName=listBoxBooks, Path=SelectedItem.End,Converter={StaticResource PlainToContentConverter},UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

但格式化丢失了。我认为这是由于缺少第二个转换器(在另一个方向),但正如我刚才指出的那样,我错了。上面的代码没有保留格式,因为它只是不以纯文本格式保存!用HtmlToContentConverter替换转换器就可以了!

无论如何,谢谢你花的时间!


0
投票

更新后,我想我明白你要做什么。所以我的理解是,您有一个书籍列表和一本书的选择,您只想更新自定义控件以反映。

如果您没有通过代码绑定的具体原因,您可以使用以下技术。 (例如,我在我的结尾做了一个快速演示)

步骤1:设置XAML直接绑定到Listbox.SelectedItem。

<Window x:Class="TestWPF.MainWindow"
    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"
    xmlns:local="clr-namespace:TestWPF"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800">

<Window.Resources>
    <local:DummyConverter x:Key="DummyConverter"/>
</Window.Resources>


<Grid Margin="15">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <ListBox x:Name="MyListOfBooks" ItemsSource="{Binding Path=BookCollection, Mode=OneWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="10">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Title, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
                    <TextBlock Text="{Binding Path=End, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, StringFormat='dddd, dd MMMM yyyy'}" Margin="30,0,0,0"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <!--Replace with custom control, make sure your custom control has a dependancy property for this binding-->
    <TextBox x:Name="MyTextBox" Grid.Column="2" Text="{Binding Path=SelectedItem.Title, ElementName=MyListOfBooks, Converter={StaticResource DummyConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10"/>

</Grid>
</Window>

第2步:这是我的演示代码以提供帮助。

namespace TestWPF
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
      MainViewModel model;
      public MainWindow()
      {
          InitializeComponent();
          this.Loaded += MainWindow_Loaded;
      }

      private void MainWindow_Loaded(object sender, RoutedEventArgs e)
      {
          model = new MainViewModel();
          model.Load();
          this.DataContext = model;
      }       
  }

  public class MainViewModel
  {
      public ObservableCollection<Book> BookCollection { get; set; }

      public void Load()
      {
          BookCollection = new ObservableCollection<Book>
          {
              new Book() { Title = "Book One", End = DateTime.Now },
              new Book() { Title = "Book Two", End = DateTime.Now.AddDays(10) },
              new Book() { Title = "Book Three", End = DateTime.Now.AddDays(2) }
          };
      }
  }

  public class Book : INotifyPropertyChanged
  {
     private string title;
     private DateTime end;

     public string Title
     {
        get { return title; }
        set
        {
            title = value;
            NotifyPropertyChanged();
        }
     }
     public DateTime End
     {
         get { return end; }
         set
         {
            end = value;
            NotifyPropertyChanged();
         }
      }

      public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
      {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }

      public event PropertyChangedEventHandler PropertyChanged;
   }


  public class DummyConverter : IValueConverter
  {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
        if (value == null)
            return null;

        System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
        return string.Join("-", encoding.GetBytes((value as string) ?? string.Empty));
      }


      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
          if (value == null)
              return null;

          string val = (value as string);

          var array = val.Split('-');
          Byte[] byteArray = new Byte[array.Length];
          for (int i = 0; i < array.Length; i++)
          {
              Byte.TryParse(array[i], out byte x);
            byteArray[i] = x;
          }

          return Encoding.ASCII.GetString(byteArray);
      }
 }
} 

如果您仍然遇到绑定问题或者如果我误解了这个问题,请告诉我。还提供自定义控件的代码。

© www.soinside.com 2019 - 2024. All rights reserved.