Metainformationen zur Seite
  •  

Unterschiede

Hier werden die Unterschiede zwischen zwei Versionen angezeigt.

Link zu dieser Vergleichsansicht

Beide Seiten der vorigen Revision Vorhergehende Überarbeitung
Nächste Überarbeitung
Vorhergehende Überarbeitung
start:visualstudio2017:programmieren:dotnetgrundlagen:tipps_tricks [2022/09/22 19:15]
wikiadmin [Working with Checkboxes in the WPF TreeView / Arbeiten mit Kontrollkästchen in der WPF TreeView]
start:visualstudio2017:programmieren:dotnetgrundlagen:tipps_tricks [2022/09/23 07:04] (aktuell)
wikiadmin [Working with Checkboxes in the WPF TreeView / Arbeiten mit Kontrollkästchen in der WPF TreeView]
Zeile 241: Zeile 241:
 I suggest you copy those requirements and paste them into your favorite text editor, such as Notepad, because we will reference them throughout the rest of the article by number. I suggest you copy those requirements and paste them into your favorite text editor, such as Notepad, because we will reference them throughout the rest of the article by number.
  
-Putting the Smarts in a ViewModel+=== Putting the Smarts in a ViewModel ===
 As explained in my ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article, the TreeView was practically designed to be used in conjunction with a ViewModel. This article takes that idea further, and shows how we can use a ViewModel to encapsulate application-specific logic related to the check state of items in the tree. In this article, we will examine my FooViewModel class, which the following interface describes: As explained in my ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article, the TreeView was practically designed to be used in conjunction with a ViewModel. This article takes that idea further, and shows how we can use a ViewModel to encapsulate application-specific logic related to the check state of items in the tree. In this article, we will examine my FooViewModel class, which the following interface describes:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +interface IFooViewModel : INotifyPropertyChanged
 +{
 +    List<FooViewModel> Children { get; }
 +    bool? IsChecked { get; set; }
 +    bool IsInitiallySelected { get; }
 +    string Name { get; }
 +}
 +</code>
 +The most interesting aspect of this ViewModel class is the logic behind the IsChecked property. This logic satisfies Requirements 2 and 3, seen previously. The FooViewModel’s IsChecked logic is below:
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +/// <summary>
 +/// Gets/sets the state of the associated UI toggle (ex. CheckBox).
 +/// The return value is calculated based on the check state of all
 +/// child FooViewModels.  Setting this property to true or false
 +/// will set all children to the same check state, and setting it 
 +/// to any value will cause the parent to verify its check state.
 +/// </summary>
 +public bool? IsChecked
 +{
 +    get { return _isChecked; }
 +    set { this.SetIsChecked(value, true, true); }
 +}
 +
 +void SetIsChecked(bool? value, bool updateChildren, bool updateParent)
 +{
 +    if (value == _isChecked)
 +        return;
 +
 +    _isChecked = value;
 +
 +    if (updateChildren && _isChecked.HasValue)
 +        this.Children.ForEach(c => c.SetIsChecked(_isChecked, true, false));
 +
 +    if (updateParent && _parent != null)
 +        _parent.VerifyCheckState();
 +
 +    this.OnPropertyChanged("IsChecked");
 +}
 +
 +void VerifyCheckState()
 +{
 +    bool? state = null;
 +    for (int i = 0; i < this.Children.Count; ++i)
 +    {
 +        bool? current = this.Children[i].IsChecked;
 +        if (i == 0)
 +        {
 +            state = current;
 +        }
 +        else if (state != current)
 +        {
 +            state = null;
 +            break;
 +        }
 +    }
 +    this.SetIsChecked(state, false, true);
 +}
 +</code>
 +
 +This strategy is specific to the functional requirements I imposed upon myself. If you have different rules regarding how and when items should update their check state, simply adjust the logic in those methods to suit your needs.
 +
 +=== TreeView Configuration ===
 +Now it is time to see how the TreeView is able to display checkboxes and bind to the ViewModel. This is entirely accomplished in XAML. The TreeView declaration is actually quite simple, as seen below:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<TreeView 
 +  x:Name="tree"
 +  ItemContainerStyle="{StaticResource TreeViewItemStyle}"
 +  ItemsSource="{Binding Mode=OneTime}"
 +  ItemTemplate="{StaticResource CheckBoxItemTemplate}"
 +  />
 +</code
 +The TreeView’s ItemsSource property is implicitly bound to its DataContext, which inherits a List<FooViewModel> from the containing window. That list only contains one ViewModel object, but it is necessary to put it into a collection because ItemsSource is of type IEnumerable.
 +
 +TreeViewItem is a container of visual elements generated by the ItemTemplate. In this demo, we assign the following HierarchicalDataTemplate to the tree's ItemTemplate property:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<HierarchicalDataTemplate 
 +  x:Key="CheckBoxItemTemplate"
 +  ItemsSource="{Binding Children, Mode=OneTime}"
 +  >
 +  <StackPanel Orientation="Horizontal">
 +    <!-- These elements are bound to a FooViewModel object. -->
 +    <CheckBox
 +      Focusable="False" 
 +      IsChecked="{Binding IsChecked}" 
 +      VerticalAlignment="Center"
 +      />
 +    <ContentPresenter 
 +      Content="{Binding Name, Mode=OneTime}" 
 +      Margin="2,0"
 +      />
 +  </StackPanel>
 +</HierarchicalDataTemplate>
 +</code>
 +
 +There are several points of interest in that template. The template includes a CheckBox whose Focusable property is set to false. This prevents the CheckBox from ever receiving input focus, which assists in meeting Requirement 4. You might be wondering how we will be able to satisfy Requirement 5 if the CheckBox never has input focus. We will address that issue later in this article, when we examine how to attach the behavior of a ToggleButton to a TreeViewItem.
 +
 +The CheckBox’s IsChecked property is bound to the IsChecked property of a FooViewModel object, but notice that its Content property is not set to anything. Instead, there is a ContentPresenter directly next to it, whose Content is bound to the Name property of a FooViewModel object. By default, clicking anywhere on a CheckBox causes it to toggle its check state. By using a separate ContentPresenter, rather than setting the CheckBox’s Content property, we can avoid that default behavior. This helps us satisfy Requirements 6 and 7. Clicking on the box element in the CheckBox will cause its check state to change, but clicking on the neighboring display text will not. Similarly, clicking on the box in the CheckBox will not select that item, but clicking on the neighboring display text will.
 +
 +We will examine the TreeView’s ItemContainerStyle in the next section.
 +
 +=== Turning a TreeViewItem into a ToggleButton ===
 +In the previous section, we quickly considered an interesting question. If the CheckBox in the TreeViewItem has its Focusable property set to false, how can it toggle its check state in response to the Spacebar or Enter key? Since an element only receives keystrokes if it has keyboard focus, it seems impossible for Requirement 5 to be satisfied. Keep in mind; we had to set the CheckBox’s Focusable property to false so that navigating from item to item in the tree does not require multiple keystrokes.
 +
 +This is a tricky problem: we cannot let the CheckBox ever have input focus because it negatively affects keyboard navigation, yet, when its containing item is selected, it must somehow toggle its check state in response to certain keystrokes. These seem to be mutually exclusive requirements. When I hit this brick wall, I decided to seek geek from the WPF Disciples, and started this thread. Not to my surprise, Dr. WPF had already encountered this type of problem and devised a brilliant-approaching-genius solution that was easy to plug into my application. The good Doctor sent me the code for a VirtualToggleButton class, and was kind enough to allow me to publish it in this article.
 +
 +The Doctor’s solution uses what John Gossman refers to as “attached behavior.” The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.
 +
 +In this article, we see how to give a TreeViewItem an attached IsChecked property that toggles when the user presses the Spacebar or Enter key. That attached IsChecked property binds to the IsChecked property of a FooViewModel object, which is also bound to the IsChecked property of the CheckBox in the TreeViewItem. This solution gives the appearance that a CheckBox is toggling its check state in response to the Spacebar or Enter key, but in reality, its IsChecked property updates in response to a TreeViewItem pushing a new value to the ViewModel’s IsChecked property via data binding.
 +
 +Before going any further, I should point out that I fully recognize that this is crazy. The fact that this is the cleanest way to implement a TreeView of checkboxes in WPF v3.5 indicates, to me, that Microsoft needs to simplify this aspect of the platform. However, until they do, this is probably the best way to implement the feature.
 +
 +In this demo, we do not make use of all features in Dr. WPF’s VirtualToggleButton class. It has support for several things that we do not need, such as handling mouse clicks and providing tri-state checkboxes. We only need to make use of its support for the attached IsVirtualToggleButton and IsChecked properties and the keyboard interaction behavior it provides.
 +
 +Here is the property-changed callback method for the attached IsVirtualToggleButton property, which is what enables this class to gain access to TreeViewItems in the tree:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +/// <summary>
 +/// Handles changes to the IsVirtualToggleButton property.
 +/// </summary>
 +private static void OnIsVirtualToggleButtonChanged(
 +  DependencyObject d, DependencyPropertyChangedEventArgs e)
 +{
 +    IInputElement element = d as IInputElement;
 +    if (element != null)
 +    {
 +        if ((bool)e.NewValue)
 +        {
 +            element.MouseLeftButtonDown += OnMouseLeftButtonDown;
 +            element.KeyDown += OnKeyDown;
 +        }
 +        else
 +        {
 +            element.MouseLeftButtonDown -= OnMouseLeftButtonDown;
 +            element.KeyDown -= OnKeyDown;
 +        }
 +    }
 +}
 +</code>
 +When a TreeViewItem raises its KeyDown event, this logic executes:
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +private static void OnKeyDown(object sender, KeyEventArgs e)
 +{
 +    if (e.OriginalSource == sender)
 +    {
 +        if (e.Key == Key.Space)
 +        {
 +            // ignore alt+space which invokes the system menu
 +            if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) 
 +                return;
 +
 +            UpdateIsChecked(sender as DependencyObject);
 +            e.Handled = true;
 +        }
 +        else if (e.Key == Key.Enter && 
 +         (bool)(sender as DependencyObject)
 +         .GetValue(KeyboardNavigation.AcceptsReturnProperty))
 +        {
 +            UpdateIsChecked(sender as DependencyObject);
 +            e.Handled = true;
 +        }
 +    }
 +}
 +
 +private static void UpdateIsChecked(DependencyObject d)
 +{
 +    Nullable<bool> isChecked = GetIsChecked(d);
 +    if (isChecked == true)
 +    {
 +        SetIsChecked(d, 
 +         GetIsThreeState(d) ? 
 +         (Nullable<bool>)null : 
 +         (Nullable<bool>)false);
 +    }
 +    else
 +    {
 +        SetIsChecked(d, isChecked.HasValue);
 +    }
 +}
 +</code>
 +The UpdateIsChecked method sets the attached IsChecked property on an element, which is a TreeViewItem in this demo. Setting an attached property on a TreeViewItem has no effect by itself. In order to have the application use that property value, it must be bound to something. In this application, it is bound to the IsChecked property of a FooViewModel object. The following Style is assigned to the TreeView’s ItemContainerStyle property. It ties a TreeViewItem to a FooViewModel object and adds the virtual ToggleButton behavior that we just examined.
 +<code XML [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem">
 +  <Setter Property="IsExpanded" Value="True" />
 +  <Setter Property="IsSelected" Value="{Binding IsInitiallySelected, Mode=OneTime}" />
 +  <Setter Property="KeyboardNavigation.AcceptsReturn" Value="True" />
 +  <Setter Property="dw:VirtualToggleButton.IsVirtualToggleButton" Value="True" />
 +  <Setter Property="dw:VirtualToggleButton.IsChecked" Value="{Binding IsChecked}" />        
 +</Style>
 +</code>
 +
 +This piece ties the entire puzzle together. Note that the attached KeyboardNavigation.AcceptsReturn property is set to true on each TreeViewItem so that the VirtualToggleButton will toggle its check state in response to the Enter key. The first Setter in the Style, which sets the initial value of each item's IsExpanded property to true, ensures that Requirement 8 is met.
 +
 +=== CheckBox Bug in Aero Theme ===
 +I must point out one strange, and disappointing, issue. The Aero theme for WPF’s CheckBox control has a problem in .NET 3.5. When it moves from the ‘Indeterminate’ state to the ‘Checked’ state, the background of the box does not update properly until you move the mouse cursor over it. You can see this in the screenshot below:
 +
 +{{:start:visualstudio2017:programmieren:tipps_tricks:screenshot_aero.png?400|}}
  
 </WRAP> </WRAP>
Zeile 276: Zeile 476:
 Ich schlage vor, Sie kopieren diese Anforderungen und fügen sie in Ihren bevorzugten Texteditor ein, z. B. in Notepad, da wir sie im weiteren Verlauf des Artikels nummerisch referenzieren werden. Ich schlage vor, Sie kopieren diese Anforderungen und fügen sie in Ihren bevorzugten Texteditor ein, z. B. in Notepad, da wir sie im weiteren Verlauf des Artikels nummerisch referenzieren werden.
  
-Die Intelligenz in ein ViewModel packen+=== Die Intelligenz in ein ViewModel packen ===
 Wie in meinem Artikel 'Simplifying the WPF TreeView by Using the ViewModel Pattern' (Vereinfachung der WPF-TreeView durch Verwendung des ViewModel-Musters) erläutert, wurde die TreeView praktisch dafür entwickelt, in Verbindung mit einem ViewModel verwendet zu werden. Dieser Artikel führt diese Idee weiter und zeigt, wie wir ein ViewModel verwenden können, um anwendungsspezifische Logik in Bezug auf den Prüfstatus von Elementen im Baum zu kapseln. In diesem Artikel werden wir meine FooViewModel-Klasse untersuchen, die durch die folgende Schnittstelle beschrieben wird: Wie in meinem Artikel 'Simplifying the WPF TreeView by Using the ViewModel Pattern' (Vereinfachung der WPF-TreeView durch Verwendung des ViewModel-Musters) erläutert, wurde die TreeView praktisch dafür entwickelt, in Verbindung mit einem ViewModel verwendet zu werden. Dieser Artikel führt diese Idee weiter und zeigt, wie wir ein ViewModel verwenden können, um anwendungsspezifische Logik in Bezug auf den Prüfstatus von Elementen im Baum zu kapseln. In diesem Artikel werden wir meine FooViewModel-Klasse untersuchen, die durch die folgende Schnittstelle beschrieben wird:
  
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +interface IFooViewModel : INotifyPropertyChanged
 +{
 +    List<FooViewModel> Children { get; }
 +    bool? IsChecked { get; set; }
 +    bool IsInitiallySelected { get; }
 +    string Name { get; }
 +}
 +</code>
 +Der interessanteste Aspekt dieser ViewModel-Klasse ist die Logik hinter der Eigenschaft IsChecked. Diese Logik erfüllt die Anforderungen 2 und 3, die zuvor gesehen wurden. Die IsChecked-Logik des FooViewModel ist unten dargestellt:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +///Ruft den Zustand des zugehörigen UI-Toggles (z.B. CheckBox) ab bzw. setzt ihn.
 +///Der Rückgabewert wird auf der Grundlage des Prüfstatus aller untergeordneten 
 +///FooViewModelle berechnet.  Wenn diese Eigenschaft auf true oder false gesetzt wird, 
 +///erhalten alle untergeordneten Modelle den gleichen Prüfstatus, 
 +///und wenn sie auf einen beliebigen Wert gesetzt wird, überprüft das übergeordnete Modell seinen Prüfstatus.
 +public bool? IsChecked
 +{
 +    get { return _isChecked; }
 +    set { this.SetIsChecked(value, true, true); }
 +}
 +
 +void SetIsChecked(bool? value, bool updateChildren, bool updateParent)
 +{
 +    if (value == _isChecked)
 +        return;
 +
 +    _isChecked = value;
 +
 +    if (updateChildren && _isChecked.HasValue)
 +        this.Children.ForEach(c => c.SetIsChecked(_isChecked, true, false));
 +
 +    if (updateParent && _parent != null)
 +        _parent.VerifyCheckState();
 +
 +    this.OnPropertyChanged("IsChecked");
 +}
 +
 +void VerifyCheckState()
 +{
 +    bool? state = null;
 +    for (int i = 0; i < this.Children.Count; ++i)
 +    {
 +        bool? current = this.Children[i].IsChecked;
 +        if (i == 0)
 +        {
 +            state = current;
 +        }
 +        else if (state != current)
 +        {
 +            state = null;
 +            break;
 +        }
 +    }
 +    this.SetIsChecked(state, false, true);
 +}
 +</code>
 +
 +Diese Strategie ist spezifisch für die funktionalen Anforderungen, die ich mir selbst auferlegt habe. Wenn Sie andere Regeln haben, wie und wann Elemente ihren Prüfstatus aktualisieren sollten, passen Sie die Logik in diesen Methoden einfach an Ihre Bedürfnisse an.
 +
 +=== TreeView Konfiguration ===
 +Nun ist es an der Zeit zu sehen, wie die TreeView in der Lage ist, Kontrollkästchen anzuzeigen und an das ViewModel zu binden. Dies wird vollständig in XAML realisiert. Die TreeView-Deklaration ist eigentlich recht einfach, wie unten zu sehen ist:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<TreeView 
 +  x:Name="tree"
 +  ItemContainerStyle="{StaticResource TreeViewItemStyle}"
 +  ItemsSource="{Binding Mode=OneTime}"
 +  ItemTemplate="{StaticResource CheckBoxItemTemplate}"
 +  />
 +</code
 +The TreeView’s ItemsSource property is implicitly bound to its DataContext, which inherits a List<FooViewModel> from the containing window. That list only contains one ViewModel object, but it is necessary to put it into a collection because ItemsSource is of type IEnumerable.
 + 
 +TreeViewItem is a container of visual elements generated by the ItemTemplate. In this demo, we assign the following HierarchicalDataTemplate to the tree's ItemTemplate property:
 + 
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<HierarchicalDataTemplate 
 +  x:Key="CheckBoxItemTemplate"
 +  ItemsSource="{Binding Children, Mode=OneTime}"
 +  >
 +  <StackPanel Orientation="Horizontal">
 +    <!-- These elements are bound to a FooViewModel object. -->
 +    <CheckBox
 +      Focusable="False" 
 +      IsChecked="{Binding IsChecked}" 
 +      VerticalAlignment="Center"
 +      />
 +    <ContentPresenter 
 +      Content="{Binding Name, Mode=OneTime}" 
 +      Margin="2,0"
 +      />
 +  </StackPanel>
 +</HierarchicalDataTemplate>
 +</code>
 +
 +In dieser Vorlage gibt es mehrere interessante Punkte. Die Vorlage enthält eine CheckBox, deren Eigenschaft Focusable auf false gesetzt ist. Dadurch wird verhindert, dass die CheckBox jemals den Eingabefokus erhält, was zur Erfüllung von Anforderung 4 beiträgt. Sie fragen sich vielleicht, wie wir die Anforderung 5 erfüllen können, wenn die CheckBox nie den Eingabefokus erhält. Wir werden dieses Problem später in diesem Artikel behandeln, wenn wir untersuchen, wie man das Verhalten eines ToggleButtons an ein TreeViewItem anhängen kann.
 +
 +Die IsChecked-Eigenschaft der CheckBox ist an die IsChecked-Eigenschaft eines FooViewModel-Objekts gebunden, aber beachten Sie, dass die Content-Eigenschaft nicht auf irgendetwas gesetzt ist. Stattdessen befindet sich direkt daneben ein ContentPresenter, dessen Inhalt an die Eigenschaft Name eines FooViewModel-Objekts gebunden ist. Wenn Sie auf eine CheckBox klicken, wird standardmäßig der Status der CheckBox umgeschaltet. Durch die Verwendung eines separaten ContentPresenters, anstatt die Content-Eigenschaft der CheckBox zu setzen, können wir dieses Standardverhalten vermeiden. Dies hilft uns, die Anforderungen 6 und 7 zu erfüllen. Wenn Sie auf das Kästchen in der CheckBox klicken, ändert sich der Status des Kontrollkästchens, aber das Klicken auf den benachbarten Anzeigetext ändert sich nicht. In ähnlicher Weise wählt ein Klick auf das Kästchen in der CheckBox dieses Element nicht aus, aber ein Klick auf den benachbarten Anzeigetext schon.
 +
 +Wir werden den ItemContainerStyle des TreeViews im nächsten Abschnitt untersuchen.
 +
 +=== Einen TreeViewItem in einen ToggleButton verwandeln ===
 +Im vorigen Abschnitt haben wir uns schnell eine interessante Frage gestellt. Wenn die CheckBox im TreeViewItem ihre Focusable-Eigenschaft auf false gesetzt hat, wie kann sie dann als Reaktion auf die Leertaste oder die Eingabetaste ihren Prüfstatus umschalten? Da ein Element nur dann Tastendrücke empfängt, wenn es den Tastaturfokus hat, scheint es unmöglich zu sein, die Anforderung 5 zu erfüllen. Denken Sie daran, dass wir die Eigenschaft Focusable der CheckBox auf false setzen mussten, damit die Navigation von Element zu Element in der Baumstruktur nicht mehrere Tastendrücke erfordert.
 +
 +Dies ist ein kniffliges Problem: Wir können nicht zulassen, dass die CheckBox jemals den Eingabefokus hat, da dies die Navigation über die Tastatur negativ beeinflusst, aber wenn das Element, das sie enthält, ausgewählt ist, muss sie irgendwie ihren Prüfstatus als Reaktion auf bestimmte Tastendrücke umschalten. Dies scheinen sich gegenseitig ausschließende Anforderungen zu sein. Als ich auf diess Hindernis stieß, beschloss ich, die WPF-Jünger um Rat zu fragen, und startete diesen Thread. Zu meiner Überraschung war Dr. WPF bereits auf diese Art von Problem gestoßen und hatte eine geniale Lösung entwickelt, die sich leicht in meine Anwendung integrieren ließ. Der gute Doktor schickte mir den Code für eine VirtualToggleButton-Klasse und war so freundlich, mir zu erlauben, ihn in diesem Artikel zu veröffentlichen.
 +
 +Die Lösung des Doktors verwendet das, was John Gossman als "angehängtes Verhalten" (attached behavior) bezeichnet. Die Idee ist, dass Sie eine angehängte Eigenschaft auf ein Element setzen, so dass Sie von der Klasse, die die angehängte Eigenschaft exponiert, Zugriff auf das Element erhalten können. Sobald diese Klasse Zugriff auf das Element hat, kann sie Ereignisse an das Element koppeln und als Reaktion auf das Auslösen dieser Ereignisse das Element Dinge tun lassen, die es normalerweise nicht tun würde. Dies ist eine sehr bequeme Alternative zum Erstellen und Verwenden von Unterklassen und ist sehr XAML-freundlich.
 +
 +In diesem Artikel sehen wir, wie man einem TreeViewItem eine angehängte IsChecked-Eigenschaft gibt, die umschaltet, wenn der Benutzer die Leertaste oder die Eingabetaste drückt. Diese angehängte IsChecked-Eigenschaft ist an die IsChecked-Eigenschaft eines FooViewModel-Objekts gebunden, das wiederum an die IsChecked-Eigenschaft der CheckBox im TreeViewItem gebunden ist. Diese Lösung erweckt den Anschein, dass eine CheckBox ihren Prüfstatus als Reaktion auf die Leertaste oder die Eingabetaste umschaltet, aber in Wirklichkeit wird ihre IsChecked-Eigenschaft als Reaktion auf ein TreeViewItem aktualisiert, das einen neuen Wert an die IsChecked-Eigenschaft des ViewModels über Datenbindung überträgt.
 +
 +Bevor ich fortfahre, sollte ich darauf hinweisen, dass mir völlig klar ist, dass dies verrückt ist. Die Tatsache, dass dies der sauberste Weg ist, eine TreeView von Kontrollkästchen in WPF v3.5 zu implementieren, zeigt mir, dass Microsoft diesen Aspekt der Plattform vereinfachen muss. Bis dahin ist dies jedoch wahrscheinlich der beste Weg, die Funktion zu implementieren.
 +
 +In dieser Demo machen wir nicht von allen Funktionen der VirtualToggleButton-Klasse von Dr. WPF Gebrauch. Sie bietet Unterstützung für mehrere Dinge, die wir nicht benötigen, wie z. B. die Verarbeitung von Mausklicks und die Bereitstellung von Checkboxen mit drei Zuständen. Wir brauchen nur die Unterstützung für die angehängten Eigenschaften IsVirtualToggleButton und IsChecked sowie das Verhalten bei der Tastaturinteraktion, das sie bietet.
 +
 +Hier ist die Callback-Methode für die angehängte IsVirtualToggleButton-Eigenschaft, die es dieser Klasse ermöglicht, Zugriff auf TreeViewItems im Baum zu erhalten:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +/// <summary>
 +/// Behandelt Änderungen an der Eigenschaft IsVirtualToggleButton.
 +/// </summary>
 +private static void OnIsVirtualToggleButtonChanged(
 +  DependencyObject d, DependencyPropertyChangedEventArgs e)
 +{
 +    IInputElement element = d as IInputElement;
 +    if (element != null)
 +    {
 +        if ((bool)e.NewValue)
 +        {
 +            element.MouseLeftButtonDown += OnMouseLeftButtonDown;
 +            element.KeyDown += OnKeyDown;
 +        }
 +        else
 +        {
 +            element.MouseLeftButtonDown -= OnMouseLeftButtonDown;
 +            element.KeyDown -= OnKeyDown;
 +        }
 +    }
 +}
 +</code>
 +Wenn ein TreeViewItem sein KeyDown Ereignis auslöst, wird diese Logik ausgeführt:
 +
 +<code C# [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +private static void OnKeyDown(object sender, KeyEventArgs e)
 +{
 +    if (e.OriginalSource == sender)
 +    {
 +        if (e.Key == Key.Space)
 +        {
 +            // ignore alt+space which invokes the system menu
 +            if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) 
 +                return;
 + 
 +            UpdateIsChecked(sender as DependencyObject);
 +            e.Handled = true;
 +        }
 +        else if (e.Key == Key.Enter && 
 +         (bool)(sender as DependencyObject)
 +         .GetValue(KeyboardNavigation.AcceptsReturnProperty))
 +        {
 +            UpdateIsChecked(sender as DependencyObject);
 +            e.Handled = true;
 +        }
 +    }
 +}
 + 
 +private static void UpdateIsChecked(DependencyObject d)
 +{
 +    Nullable<bool> isChecked = GetIsChecked(d);
 +    if (isChecked == true)
 +    {
 +        SetIsChecked(d, 
 +         GetIsThreeState(d) ? 
 +         (Nullable<bool>)null : 
 +         (Nullable<bool>)false);
 +    }
 +    else
 +    {
 +        SetIsChecked(d, isChecked.HasValue);
 +    }
 +}
 +</code>
 +Die UpdateIsChecked-Methode setzt die angehängte IsChecked-Eigenschaft auf ein Element, das in dieser Demo ein TreeViewItem ist. Das Setzen einer angehängten Eigenschaft auf einem TreeViewItem hat selbst keinen Effekt. Damit die Anwendung diesen Eigenschaftswert verwenden kann, muss er an etwas gebunden sein. In dieser Anwendung ist sie an die IsChecked Eigenschaft eines FooViewModel Objekts gebunden. Der folgende Style wird der ItemContainerStyle Eigenschaft des TreeViews zugewiesen. Er bindet ein TreeViewItem an ein FooViewModel Objekt und fügt das virtuelle ToggleButton Verhalten hinzu, das wir gerade untersucht haben.
 +
 +<code XML [enable_line_numbers="true",highlight_lines_extra="0,"]>
 +<Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem">
 +  <Setter Property="IsExpanded" Value="True" />
 +  <Setter Property="IsSelected" Value="{Binding IsInitiallySelected, Mode=OneTime}" />
 +  <Setter Property="KeyboardNavigation.AcceptsReturn" Value="True" />
 +  <Setter Property="dw:VirtualToggleButton.IsVirtualToggleButton" Value="True" />
 +  <Setter Property="dw:VirtualToggleButton.IsChecked" Value="{Binding IsChecked}" />        
 +</Style>
 +</code>
 +Dieses Teil fügt das gesamte Puzzle zusammen. Beachten Sie, dass die angehängte Eigenschaft KeyboardNavigation.AcceptsReturn für jedes TreeViewItem auf true gesetzt ist, so dass der VirtualToggleButton seinen Prüfstatus als Reaktion auf die Enter-Taste umschaltet. Der erste Setter im Style, der den Anfangswert der IsExpanded-Eigenschaft jedes Elements auf true setzt, stellt sicher, dass Anforderung 8 erfüllt ist.
 +
 +=== CheckBox-Fehler im Aero-Design ===
 +Ich muss auf ein seltsames und enttäuschendes Problem hinweisen. Das Aero-Thema für das CheckBox-Steuerelement von WPF hat ein Problem in .NET 3.5. Wenn es vom Zustand "Unbestimmt" in den Zustand "Geprüft" wechselt, wird der Hintergrund des Kästchens nicht richtig aktualisiert, bis Sie den Mauszeiger darüber bewegen. Sie können dies im folgenden Screenshot sehen:
 +
 +{{:start:visualstudio2017:programmieren:tipps_tricks:screenshot_aero.png?400|}}
 </WRAP> </WRAP>
 </WRAP> </WRAP>
  
 +[[https://www.codeproject.com/Articles/28306/Working-with-Checkboxes-in-the-WPF-TreeView|Original Artike von Josh Smith.]] [[https://www.deepl.com/translator]|Erste Übersetzung mit Deepl.] [[|]]