我無法從ListBoxin獲取專案容器Backstage。說,我有以下內容Backstage:
<!-- Backstage -->
<r:Ribbon.Menu>
<r:Backstage x:Name="backStage">
<r:BackstageTabControl>
<r:BackstageTabItem Header="Columns">
<Grid>
<ListBox Grid.Row="1" Grid.Column="0" x:Name="lstColumns"/>
</Grid>
</r:BackstageTabItem>
</r:BackstageTabControl>
</r:Backstage>
</r:Ribbon.Menu>
我填寫:
public Root()
{
ContentRendered = delegate
{
var list = new List<int> { 1, 2, 3 };
foreach (var index in list)
{
lstColumns.Items.Add(index);
}
};
}
接下來,我想ListBoxItem從 的第一個條目中檢索專案容器(在本例中為 - )ListBox:
private void OnGetProperties(object sender, RoutedEventArgs e)
{
// Get first item container
var container = lstColumns.ItemContainerGenerator.ContainerFromIndex(0);
if (container is not null)
{
MessageBox.Show($"container = {container.GetType().FullName}");
}
else
{
MessageBox.Show("container is null");
}
}
但container總是null。但!如果我打開Backstage然后隱藏它,我會看到以下訊息:
container = System.Windows.Controls.ListBoxItem.
所以,我決定添加Backstage在填充之前打開的代碼:
backStage.IsOpen = true;
var list = new List<int> { 1, 2, 3 };
foreach (var index in list)
{
lstColumns.Items.Add(index);
}
backStage.IsOpen = false;
這可行,但是當您幾乎看不到Backstage顯示和隱藏時會閃爍。這不是完美的解決方案。那么,如何獲取物品容器呢?
PS 測驗專案在這里。
更新(解釋)
The reason I need the item container is that I need to add set CheckBox state upon filling ListBox. This ListBoxis styled to contain CheckBoxes for items:
<Window.Resources>
<Style x:Key="CheckBoxListStyle" TargetType="ListBox">
<Setter Property="SelectionMode" Value="Multiple"/>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Margin" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<CheckBox Focusable="False"
IsChecked="{Binding Path=IsSelected,
Mode=TwoWay,
RelativeSource={RelativeSource TemplatedParent}}">
<ContentPresenter />
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
So, when I add text in the loop above, the CheckBoxgets created. I, then, need to set the states of those checkboxes, which come from JSON. So, I need something like this:
var list = new List<int> { 1, 2, 3 };
var json = JsonNode.Parse("""
{
"checked": true
}
""");
foreach (var index in list)
{
CheckBox checkBox = null;
var pos = lstColumns.Items.Add(index);
var container = lstColumns.ItemContainerGenerator.ContainerFromIndex(pos);
// Reach checkbox
// ...
// checkBox = ...
// ...
checkBox.IsChecked = json["checked"].GetValue<bool>();
}
And the problem is that container is always null.
Also, it doesn't matter whether I use Loaded or ContentRendered event - in either case container is null.
uj5u.com熱心網友回復:
高級介紹
ContainerFromIndex回傳的原因null是容器根本沒有實作。
回傳與 ItemCollection 中給定索引處的專案相對應的元素,
null如果專案未實作,則回傳。
這由負責以下操作的ItemContainerGenerator控制。
維護多項控制元件的資料視圖(例如)
ContainerFromElement與相應UIElement任務之間的關聯。
UIElement代表多專案控制元件生成專案。
AListBox是ItemsControl公開ItemsSource用于系結或分配集合的屬性的 an。
用于生成 ItemsControl 內容的集合。默認值為
null.
另一種選擇是簡單地將專案添加到ItemsXAML 或代碼中的集合中。
用于生成 ItemsControl 內容的集合。默認為空集合。[...]
訪問集合物件本身的屬性是只讀的,而集合本身是可讀寫的。
該Items屬性是 type 的ItemCollection,它也是一個 view。
如果你有一個
ItemsControl,比如一個ListBox有內容的,你可以使用該Items屬性來訪問ItemCollection一個視圖。因為它是一個視圖,所以您可以使用與視圖相關的功能,例如排序、過濾和分組。請注意,當ItemsSource設定時,視圖操作委托給ItemsSource集合上的視圖。因此,ItemCollection只有在委托視圖支持時,它們才支持排序、過濾和分組。
您不能同時使用兩者ItemsSource,Items它們是相關的。
[...] 您使用
Items或ItemsSource屬性來指定用于生成ItemsControl. 設定ItemsSource屬性后,Items集合將變為只讀且大小固定。
兩者ItemsSource都Items維護對資料項的參考或系結資料項,這些都不是容器。ItemContainerGenerator負責創建用戶界面元素或容器等,并維護資料與這些專案之間的ListBoxItem關系。這些容器不僅存在于應用程式的整個生命周期中,它們還會根據需要創建和銷毀。什么時候發生?這取決于。容器被創建或實作(使用內部術語)當它們顯示在 UI 中時。這就是為什么您只有在容器首次顯示后才能訪問它。它們實際存在多長時間取決于互動、虛擬化或容器回收等因素。我所說的互動是指任何形式的更改視口,這是您實際可以看到的串列的一部分。每當專案滾動到視圖中時,當然需要實作它們。對于包含數萬個專案的大型串列,提前實作所有容器或在實作后保留所有容器會影響性能并大幅增加記憶體消耗。這就是虛擬化發揮作用的地方。請參閱顯示大型資料集以供參考。
UI Virtualization is an important aspect of list controls. UI virtualization should not be confused with data virtualization. UI virtualization stores only visible items in memory but in a data-binding scenario stores the entire data structure in memory. In contrast, data virtualization stores only the data items that are visible on the screen in memory.
By default, UI virtualization is enabled for the ListView and ListBox controls when their list items are bound to data.
This implies that containers are deleted, too. Additionally, there is container recycling:
When an
ItemsControlthat uses UI virtualization is populated, it creates an item container for each item that scrolls into view and destroys the item container for each item that scrolls out of view. Container recycling enables the control to reuse the existing item containers for different data items, so that item containers are not constantly created and destroyed as the user scrolls the ItemsControl. You can choose to enable item recycling by setting theVirtualizationModeattached property toRecycling.
The consequence of virtualization and container recycling is that containers for all items are not realized in general. There are only containers for a subset of your bound or assigned items and they may be recycled or detached. That is why it is dangerous to directly reference e.g. ListBoxItems. Even if virtualization is disabled, you can run into problems like yours, trying to access user interface elements with a different lifetime than your data items.
In essence, your approach can work, but I recommend a different approach that is much more stable and robust and compatible with all of the aforementioned caveats.
A Low-Level View
What is actually happening here? Let us explore the code in medium depth, as my wrists already hurt.
Here is the ContainerFromIndex method in the reference source of .NET.
- The
forloop in line 931 iteratesItemBlocks using theNextproperty of the_itemMap. - When your items were not shown, yet in the user interface, they are not realized.
- In this case,
Nextwill return anUnrealizedItemBlock(derivative ofItemBlock). - This item block will have a property
ItemCountof zero. - The
ifcondition in line 933 will not be met. - This continues until the item blocks are iterated and
nullis returned in line 954..
Once the ListBox and its items are shown, the Next iterator will return a RealizedItemBlock which has an ItemCount of greater than zero and will therefore yield an item.
How are the containers realized then? There are methods to generate containers.
DependencyObject IItemContainerGenerator.GenerateNext(), see line 230.DependencyObject IItemContainerGenerator.GenerateNext(out bool isNewlyRealized), see line 239.
These are called in various places, like VirtualizingStackPanel - for virtualization.
protected internal override void BringIndexIntoView(int index), see line 1576, which does exactly what it is called. When an item with a certain index needs to be brought into view, e.g. through scrolling, the panel needs to create the item container in order to show the item in the user interface.private void MeasureChild(...), see line 8005. This method is used when calculating the space needed to display aListView, which is influenced by the number and size of its items as needed.- ...
Over lots of indirections from a high-level ListBox over its base type ItemsControl, ultimately, the ItemContainerGenerator is called to realize items.
An MVVM Compliant Solution
For all the previously stated issues, there is a simple, yet superior solution. Separate your data and application logic from the user interface. This can be done using the MVVM design pattern. For an introduction, you can refer to the Patterns - WPF Apps With The Model-View-ViewModel Design Pattern article by Josh Smith.
In this solution I use the Microsoft.Toolkit.Mvvm NuGet package from Microsoft. You can find an introduction and a detailed documentation here. I use it because for MVVM in WPF you need some boilerplate code for observable objects and commands that would bloat the example for a beginner. It is a good library to start and later learn the details of how the tools work behind the scenes.
So let us get started. Install the aforementioned NuGet package in a new solution. Next, create a type that represents our data item. It only contains two properties, one for the index, which is read-only and one for the checked state that can be changed. Bindings only work with properties, that is why we use them instead of e.g. fields. The type derives from ObservableObject which implements the INotifyPropertyChanged interface. This interface needs to be implemented to be able to notify that property values changed, otherwise the bindings that are introduced later will not know when to update the value in the user interface. The ObservableObject base type already provides a SetProperty method that will take care of setting a new value to the backing field of a property and automatically notify its change.
using Microsoft.Toolkit.Mvvm.ComponentModel;
namespace RibbonBackstageFillTest
{
public class JsonItem : ObservableObject
{
private bool _isChecked;
public JsonItem(int index, bool isChecked)
{
Index = index;
IsChecked = isChecked;
}
// ...read-only property assumed here.
public int Index { get; }
public bool IsChecked
{
get => _isChecked;
set => SetProperty(ref _isChecked, value);
}
// ...other properties.
}
}
Now we implement a view model for your Root view, which holds the data for the user interface. It exposes an ObservableCollection<JsonItem> property that we use to store the JSON data items. This special collection automatically notifies if any items were added, removed or replaced. This is not necessary for your example, but you I guess it could be useful for you later. You can also replace the whole collection, as we again derived from ObservableObject and use SetProperty. The GetPropertiesCommand is a command, which is just an encapsulated action, an object that performs a task. It can be bound and replaces the Click handler later. The CreateItems method simply creates a list like in your example. The GetProperties is the method where you iterate the list and set your values from JSON. Adapt the code to your needs.
using System.Collections.ObjectModel;
using System.Windows.Input;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
namespace RibbonBackstageFillTest
{
public class RootViewModel : ObservableObject
{
private ObservableCollection<JsonItem> _jsonItems;
public RootViewModel()
{
JsonItems = CreateItems();
GetPropertiesCommand = new RelayCommand(GetProperties);
}
public ObservableCollection<JsonItem> JsonItems
{
get => _jsonItems;
set => SetProperty(ref _jsonItems, value);
}
public ICommand GetPropertiesCommand { get; }
private ObservableCollection<JsonItem> CreateItems()
{
return new ObservableCollection<JsonItem>
{
new JsonItem(1, false),
new JsonItem(2, true),
new JsonItem(3, false),
new JsonItem(4, true),
new JsonItem(5, false)
};
}
private void GetProperties()
{
foreach (var jsonItem in JsonItems)
{
jsonItem.IsChecked = // ...set your JSON values here.
}
}
}
}
The code-behind of your Root view is now reduced to its essentials, no data anymore.
using Fluent;
using Fluent.Localization.Languages;
using System.Threading;
using System.Windows;
namespace RibbonBackstageFillTest
{
public partial class Root
{
public Root()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
ContentRendered = delegate
{
if (Thread.CurrentThread.CurrentUICulture.Name != "en-US")
{
RibbonLocalization.Current.LocalizationMap.Clear();
RibbonLocalization.Current.Localization = new English();
}
};
}
}
}
At last, we create the XAML for the Root view. I have added comments for you to follow along. In essence, we add the new RootViewModel as DataContext and use data-binding to connect our data item collection with the ListBox via the ItemsSource property. Furthermore, we use a DataTemplate to define the appearance of the data in the user interface and bind the Button to a command.
<r:RibbonWindow x:Class="RibbonBackstageFillTest.Root"
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:r="urn:fluent-ribbon"
xmlns:local="clr-namespace:RibbonBackstageFillTest"
mc:Ignorable="d"
Title="Backstage Ribbon"
Height="450"
Width="800">
<r:RibbonWindow.DataContext>
<!-- This creates an instance of the root view model and assigns it as data context. -->
<local:RootViewModel/>
</Window.DataContext>
<Window.Resources>
<Style x:Key="CheckBoxListStyle"
TargetType="ListBox">
<Setter Property="SelectionMode" Value="Multiple" />
<!-- This is only used to style the containers, we do not need to change the control template -->
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Margin" Value="2" />
</Style>
</Setter.Value>
</Setter>
<!-- An item template is used to define the appearance of a data item. -->
<Setter Property="ItemTemplate">
<Setter.Value>
<!-- We create a data template for our custom item type. -->
<DataTemplate DataType="local:JsonItem">
<!-- The binding will loosely connect the IsChecked property of CheckBox with the IsChecked property of its JsonItem. -->
<!-- The binding is TwoWay by default, meaning that you can change IsChecked in code or in the UI by clicking the CheckBox. -->
<!-- The IsChecked value will always be synchronized in the view and view model. -->
<CheckBox Focusable="False"
IsChecked="{Binding Path=IsChecked}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</r:RibbonWindow.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<r:Ribbon Grid.Row="0">
<!-- Backstage -->
<r:Ribbon.Menu>
<r:Backstage>
<r:BackstageTabControl>
<r:BackstageTabItem Header="Columns">
<Grid>
<!-- No need for a name anymore, we do not need to access controls. -->
<!-- The binding loosely connects the JsonItems collection with the ListBox. -->
<ListBox ItemsSource="{Binding JsonItems}"
Style="{StaticResource CheckBoxListStyle}"/>
</Grid>
</r:BackstageTabItem>
</r:BackstageTabControl>
</r:Backstage>
</r:Ribbon.Menu>
<!-- Tabs -->
<r:RibbonTabItem Header="Home">
<r:RibbonGroupBox Header="ID">
<!-- Instead of a Click event handler, we bind a command in the view model. -->
<r:Button Size="Large"
LargeIcon="pack://application:,,,/RibbonBackstageFillTest;component/img/PropertySheet.png"
Command="{Binding GetPropertiesCommand}"
Header="Properties"/>
</r:RibbonGroupBox>
</r:RibbonTabItem>
</r:Ribbon>
</Grid>
</r:RibbonWindow>
Now what is the difference? The data and your application logic is separated from the user interface. The data is always there in the view model, regardless of an item container. In fact, your data does not even know that there is a container or a ListBox. Whether the backstage is open or not, does not matter anymore, as you directly act on your data, not the user interface.
A Quicker And Dirtier Solution
I do not recommend this solution, it is just a quick and dirty solution apart from MVVM that might be easier to follow for you after you saw how to do it right. It uses the JsonItem type from before, but this time without an external library. Now you see what INotifyPropertyChanged does under the hood.
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace RibbonBackstageFillTest
{
public class JsonItem : INotifyPropertyChanged
{
private bool _isChecked;
public JsonItem(int index, bool isChecked)
{
Index = index;
IsChecked = isChecked;
}
// ...read-only property assumed here.
public int Index { get; }
public bool IsChecked
{
get => _isChecked;
set
{
if (_isChecked == value)
return;
_isChecked = value;
OnPropertyChanged();
}
}
// ...other properties.
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
In your code-behind of the Root view, just create a field _jsonItems that stores the items. This field is used to access the list later in order to change the IsChecked values.
using Fluent;
using Fluent.Localization.Languages;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
namespace RibbonBackstageFillTest
{
public partial class Root
{
private List<JsonItem> _jsonItems;
public Root()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
ContentRendered = delegate
{
if (Thread.CurrentThread.CurrentUICulture.Name != "en-US")
{
RibbonLocalization.Current.LocalizationMap.Clear();
RibbonLocalization.Current.Localization = new English();
}
};
_jsonItems = new List<JsonItem>
{
new JsonItem(1, false),
new JsonItem(2, true),
new JsonItem(3, false),
new JsonItem(4, true),
new JsonItem(5, false)
};
lstColumns.ItemsSource = _jsonItems;
}
private void OnGetProperties(object sender, RoutedEventArgs e)
{
foreach (var jsonItem in _jsonItems)
{
jsonItem.IsChecked = // ...set your JSON value.
}
}
}
}
At last for the Root view not much changes. We copy the style with the data template from the MVVM sample and set it to the ListBox. It will just behave the same, as your data is not dependent on view containers.
<r:RibbonWindow.Resources>
<Style x:Key="CheckBoxListStyle"
TargetType="ListBox">
<Setter Property="SelectionMode" Value="Multiple" />
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Margin" Value="2" />
</Style>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate DataType="local:JsonItem">
<CheckBox Focusable="False"
IsChecked="{Binding Path=IsChecked}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</r:RibbonWindow.Resources>
<ListBox x:Name="lstColumns"
Style="{StaticResource CheckBoxListStyle}"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436195.html
標籤:c# wpf xaml fluent-ribbon itemcontainergenerator
上一篇:將WebView2映射到相對路徑
下一篇:已發布事件未訂閱或未發布
