2014-10-06 28 views
5

我有一个问题,在我看来,在ListBox控件中显示ReactiveList的内容。当我尝试通过代码隐藏绑定绑定它时(使用this.OneWayBind(...)),列表保持空白。我正在使用最新的ReactiveUI版本(6.1.0)。如果我将绑定更改为XAML-Binding并删除对OneWayBind(...)的调用,则列表将显示五个String元素。如何使用代码隐藏将ReactiveList绑定到WPF ListBox或ListView?

我不知道为什么这不起作用,一个简单的TextBlock.Text联系按预期工作(请参阅代码)。


MainWindow.xaml

<Window x:Class="View_Location_Test.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:local="clr-namespace:View_Location_Test" 
    xmlns:System="clr-namespace:System;assembly=mscorlib" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<StackPanel> 
    <ListBox x:Name="ToasterList"> 
    <!-- This is working if you uncomment the above line and remove the OneWayBind call in the view-code: --> 
    <!--<ListBox x:Name="ToasterList" ItemsSource="{Binding ToasterList}">--> 
     <ListBox.Resources> 
      <DataTemplate DataType="{x:Type System:String}"> 
       <TextBlock Text="{Binding}" /> 
      </DataTemplate> 
     </ListBox.Resources> 
    </ListBox> 
    <TextBlock x:Name="ToasterName" /> 
</StackPanel> 

MainWindow.xaml.cs

public partial class MainWindow : Window, IViewFor<ViewModel> 
{ 
    public MainWindow() 
    { 
     ViewModel = new ViewModel(); 
     DataContext = ViewModel; 

     InitializeComponent(); 

     // bind 
     this.OneWayBind(ViewModel, vm => vm.ToasterList, v => v.ToasterList.ItemsSource); 
     this.Bind(ViewModel, vm => vm.Name, v => v.ToasterName.Text); 
    } 

    public ViewModel ViewModel 
    { 
     get { return (ViewModel)GetValue(ViewModelProperty); } 
     set { SetValue(ViewModelProperty, value); } 
    } 

    public static readonly DependencyProperty ViewModelProperty = 
     DependencyProperty.Register("ViewModel", typeof(ViewModel), typeof(MainWindow), new PropertyMetadata(null)); 

    object IViewFor.ViewModel 
    { 
     get { return ViewModel; } 
     set { ViewModel = (ViewModel)value; } 
    } 
} 

ViewModel.cs

public class ViewModel : ReactiveObject 
{ 
    public ViewModel() 
    { 
     ToasterList.Add("Toaster 1"); 
     ToasterList.Add("Toaster 2"); 
     ToasterList.Add("Toaster 3"); 
     ToasterList.Add("Toaster 4"); 
     ToasterList.Add("Toaster 5"); 
    } 

    private String name = "My name"; 
    public String Name 
    { 
     get { return name; } 
     set { this.RaiseAndSetIfChanged(ref name, value); } 
    } 

    private ReactiveList<String> toasterList = new ReactiveList<string>(); 
    public ReactiveList<String> ToasterList 
    { 
     get { return toasterList; } 
     set { this.RaiseAndSetIfChanged(ref toasterList, value); } 
    } 
} 

回答

3

这是因为你在一个不可思议的方式™设置ItemsTemplate,所以ReactiveUI认为你没有ItemsTemplate,并建立基于惯例,一个(这是矫枉过正只是一个字符串)。

相反,将其设置是这样的:

<ListBox x:Name="ToasterList"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding}" /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>