gpt4 book ai didi

c# - 如何使用代码隐藏将 ReactiveList 绑定(bind)到 WPF ListBox 或 ListView?

转载 作者:太空狗 更新时间:2023-10-29 23:30:54 25 4
gpt4 key购买 nike

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

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


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); }
}
}

最佳答案

这是因为您以 Weird Way™ 设置了 ItemsTemplate,因此 ReactiveUI 认为您没有 ItemsTemplate 并且正在设置基于约定的模板(这对于一个字符串来说太过分了)。

相反,设置如下:

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

关于c# - 如何使用代码隐藏将 ReactiveList 绑定(bind)到 WPF ListBox 或 ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26214017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com