简体   繁体   English

如何在 C# 中使用 Community

[英]How do I bind an object that is periodically modified to a treeview in C# WPF using the CommunityToolkit.MVVM?

I have a treeView defined in XAML as:我在treeView中定义了一个 treeView 为:


    <UserControl.Resources>
        <models:TreeLines x:Key="myLines" x:Name="myLinesData"/>
    </UserControl.Resources>


        <TreeView x:Name="treeData"
            Grid.Column="1" Background="#282828" BorderThickness="0" Padding="0,5,0,0"
                  SelectedValuePath="Uid">
                 <TreeViewItem x:Name="tLines" 
                        ItemsSource="{Binding Source={StaticResource myLines}, Path=MyLines}"
                        Style="{StaticResource custTVItem}" Header="Lines" Uid="tabLines">
                <TreeViewItem.Resources>
                    <HierarchicalDataTemplate DataType="{x:Type models:Lines}"
                                          ItemsSource="{Binding lineSet}">
                        <TextBlock Text="{Binding productName}"/>
                    </HierarchicalDataTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type models:LineSets}"
                                          ItemsSource="{Binding lineName}">
                        <TextBlock Text="{Binding setName}"/>
                    </HierarchicalDataTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type models:LineNames}"
                                              ItemsSource="{Binding dataTypes}">
                        <TextBlock Text="{Binding lineName}"/>
                    </HierarchicalDataTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type models:LineData}"
                                              ItemsSource="{Binding dataVals}">
                        <TextBlock Text="{Binding dataType}"/>
                    </HierarchicalDataTemplate>
                </TreeViewItem.Resources>
            </TreeViewItem>
        </TreeView>

The UserControl.Resources is pointing towards a class: UserControl.Resources指向 class:

public partial class TreeLines : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(MainWindow.treeData.ItemsSource))]
    private List<Lines>? myLines;
}

The error I get here is:我在这里得到的错误是:

The target(s) of [NotifyPropertyChangedFor] must be a (different) accessible property [NotifyPropertyChangedFor] 的目标必须是(不同的)可访问属性

The object myLines I'm trying to bind to has the classes behind, as seen in the TreeView `HierarchicalDataTemplates:我试图绑定到的 object myLines有后面的类,如TreeView `HierarchicalDataTemplates 中所示:

    public class Lines
    {
        public string productName { get; set; }
        public List<LineSets> lineSet { get; set; }
    }

    public class LineSets
    {
        public string setName { get; set; }
        public List<LineNames> lineName { get; set; }
    }

    public class LineNames
    {
        public string lineName { get; set; }
        public List<LineData> dataTypes { get; set; }
    }

    public class LineData
    {
        public string dataType { get; set; }
        public List<double> dataVals { get; set; }
    }

If I remove all the CommunityToolkit.MVVM aspects and set my variable: private List<Lines>? myLines;如果我删除所有 CommunityToolkit.MVVM 方面并设置我的变量: private List<Lines>? myLines; private List<Lines>? myLines; manually by changing it to public and assigning data to it on loading, then it populates on load only.通过手动将其更改为公共并在加载时为其分配数据,然后仅在加载时填充。

I need to modify myLines on the fly within my C# code which in-turn should update the treeView.我需要在我的 C# 代码中即时修改myLines ,这反过来又应该更新 treeView。 You can see I'm trying to achieve this automatically with the data binding but something isn't right.您可以看到我正在尝试通过数据绑定自动实现这一点,但有些事情是不对的。

I think the mistakes could possibly be in the line:我认为错误可能在于:

[NotifyPropertyChangedFor(nameof(MainWindow.treeData.ItemsSource))]

and/or possibly the StaticResource usage in XAML:和/或可能在 XAML 中使用StaticResource

<TreeViewItem x:Name="tLines" 
                        ItemsSource="{Binding Source={StaticResource myLines}, Path=linesCollection}"
                        Style="{StaticResource custTVItem}" Header="Lines" Uid="tabLines">

Please advise if you can help请告知您是否可以提供帮助

Replace all List<T> properties with ObservableCollection<T> .将所有List<T>属性替换为ObservableCollection<T> Then the view will be updated whenever you add or remove items from these collections.然后,每当您从这些 collections 添加或删除项目时,视图都会更新。

For the view to also update when you change a property of an individual item in a collection, the class of the property that you change should implement the INotifyPropertyChanged interface and raise change notifications.为了在您更改集合中单个项目的属性时也更新视图,您更改的属性的 class 应该实现INotifyPropertyChanged接口并引发更改通知。

Here is an example of how you should implement the Lines class:下面是如何实现 class Lines的示例:

public class Lines : ObservableObject
{
    [ObservableProperty]
    private string productName { get; set; }

    [ObservableProperty]
    private ObservableCollection<LineSets> lineSet { get; set; }
}

Bind to the generated properties (starting with an uppercase letter):绑定到生成的属性(以大写字母开头):

<HierarchicalDataTemplate DataType="{x:Type models:Lines}"
                          ItemsSource="{Binding LineSet}">
    <TextBlock Text="{Binding ProductName}"/>
</HierarchicalDataTemplate>

[NotifyPropertyChangedFor(nameof(MainWindow.treeData.ItemsSource))] does not need to be added. [NotifyPropertyChangedFor(nameof(MainWindow.treeData.ItemsSource))]不需要添加。

There is no need to implement additional notifications.无需实施额外的通知。 Because [ObservableProperty] is already implementing the notification function.因为[ObservableProperty]已经在实现通知 function。 在此处输入图像描述 Check out the auto-generated sources.查看自动生成的来源。

[NotifyPropertyChangedFor(parameter)] 's parameter should be the name of property inside the class. [NotifyPropertyChangedFor(parameter)]的参数应该是 class 内的属性名称。

public partial class TreeLines : ObservableObject
{
    [ObservableProperty]
    private List<Lines>? myLines;

    public string OtherProperty1 { get; set; }
    public string OtherProperty2 { get; set; }
}

In this case, the possible Arguments of [NotifyPropertyChangedFor] are only MyLines, OtherProperty1, and OtherProperty2.在这种情况下, [NotifyPropertyChangedFor]可能的Arguments只有MyLines、OtherProperty1和OtherProperty2。

[NotifyPropertyChangedFor] is an attribute indicating that other properties connected within the class have changed [NotifyPropertyChangedFor]是一个属性,指示 class 内连接的其他属性已更改

Here's an example.这是一个例子。

public partial class GetSum : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Sum))]
    private int num1;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Sum))]
    private int num2;

    public int Sum { get => num1 + num2; }
}

When calling the setter of Num1 Property, simultaneously update the Num1 value and Sum value bound to the screen.在调用 Num1 属性的 setter 时,同时更新屏幕绑定的 Num1 值和 Sum 值。

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp2"
        Height="450" Width="800">
    <Window.DataContext>
        <local:GetSum/>
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding Num1}"/>
        <TextBox Text="{Binding Num2}"/>
        <TextBlock Text="{Binding Sum}"/>
    </StackPanel>
</Window>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# CommunityToolkit.Mvvm ObservableProperty 列表 - C# CommunityToolkit.Mvvm ObservableProperty on a list 如何使用 CommunityToolkit.Mvvm 调用事件 - How to call events using CommunityToolkit.Mvvm 使用 CommunityToolkit.Mvvm 处理可观察对象属性 - Handling observable object properties with CommunityToolkit.Mvvm 显示 ObservableGroupedCollection 的正确方法<string, telement>使用 Wpf .NET 6 和 CommunityToolkit.Mvvm 包</string,> - Proper way of displaying an ObservableGroupedCollection<string, TElement> using Wpf .NET 6 and the CommunityToolkit.Mvvm Package 如何将 CommunityToolkit.Mvvm 中的源代码生成器用于 .NET 框架 4.7.2 WPF 应用程序 - How to use the source generators from CommunityToolkit.Mvvm for a .NET Framework 4.7.2 WPF Application 使用 CommunityToolkit.Mvvm 通知 CanExecuteChanged 的 RelayCommand 时出现 StackOverflow 异常 - StackOverflow Exception when notifying RelayCommand of CanExecuteChanged using CommunityToolkit.Mvvm 使用 CommunityToolkit.Mvvm 在 ObservableProperty 更改时调用方法 - Call method when ObservableProperty changes using CommunityToolkit.Mvvm CommunityToolkit.MVVM 的依赖注入如何工作? - How does the dependency injection with the CommunityToolkit.MVVM work? WinUI 3 CommunityToolkit Datagrid 在使用 CommunityToolkit.Mvvm 时显示来自两个模型的数据 - WinUI 3 CommunityToolkit Datagrid displaying data from two models while using CommunityToolkit.Mvvm 如何将 ObservableConcurrentDictionary 绑定到 WPF TreeView - How do I bind an ObservableConcurrentDictionary to WPF TreeView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM