简体   繁体   English

如何获取WPF ListBoxItem属性的值

[英]How to get value of a property of the WPF ListBoxItem

Hello I am trying to set the value of a property of my ListBoxItem, just not sure how to use Binding in this case if someone could help me, I appreciate it since! 您好,我正在尝试设置ListBoxItem属性的值,只是不确定如果有人可以帮助我,在这种情况下如何使用Binding,因此,我非常感谢!

Below XAML XAML以下

<ControlTemplate TargetType="controls:ModernVerticalMenu">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="{TemplateBinding ListWidth}"/>
            <ColumnDefinition Width="{TemplateBinding ListWidth}"/>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <Border Background="{TemplateBinding BackColor}" Height="{TemplateBinding Height}" BorderThickness="1" BorderBrush="{DynamicResource bordaSuperior}">
            <!-- link list -->
            <ListBox x:Name="LinkList" ItemsSource="{Binding Links, RelativeSource={RelativeSource TemplatedParent}}"  
                                     ScrollViewer.HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" >

                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid Height="50" Background="Transparent" Width="500">
                            <Border Name="border" Padding="10">
                                <Path x:Name="icon" Data="{Binding IconData}" Stretch="Fill" Fill="{DynamicResource Accent}" Width="20" Height="20" HorizontalAlignment="Left" VerticalAlignment="Center" />
                            </Border>
                            <TextBlock x:Name="texto" ToolTip="{Binding Tooltip}"  Text="{Binding DisplayName}" Margin="45,2,2,2" FontSize="{DynamicResource MediumFontSize}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" HorizontalAlignment="Left" />
                        </Grid>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding IconData}" Value="{x:Null}">
                                <Setter Property="Margin" TargetName="texto">
                                    <Setter.Value>
                                        <Thickness Bottom="2" Top="2" Left="10" Right="2"/>
                                    </Setter.Value>
                                </Setter>
                            </DataTrigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Trigger.Setters>
                                    <Setter Property="Fill" TargetName="icon">
                                        <Setter.Value>
                                            <SolidColorBrush Color="#f2f2f2" />
                                        </Setter.Value>
                                    </Setter>
                                </Trigger.Setters>
                            </Trigger>
                        </DataTemplate.Triggers>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="ListBoxItem.IsMouseOver" SourceName="LinkList" Value="true">
            <Trigger.Setters>

                <Setter Property="SelectedLinkGroup" Value="{Binding Source=LinkList,Path=Children}"/>
            </Trigger.Setters>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

In the code below I am trying to set the value SelectedLinkGroup From property to the value of Children referring to the ListBoxItem LinkList. 在下面的代码中,我尝试将值SelectedLinkGroup From属性设置为引用ListBoxItem LinkList的Children的值。

<Setter Property="SelectedLinkGroup" Value="{Binding Source=LinkList,Path=Children}"/>
using FirstFloor.ModernUI.Presentation;
using System;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace FirstFloor.ModernUI.Windows.Controls
{
    /// <summary>
    /// Represents a control that contains multiple pages that share the same space on screen.
    /// </summary>
    public class ModernVerticalMenu
        : Control
    {
        /// <summary>
        /// Identifies the ContentLoader dependency property.
        /// </summary>
        public static readonly DependencyProperty ContentLoaderProperty = DependencyProperty.Register("ContentLoader", typeof(IContentLoader), typeof(ModernVerticalMenu), new PropertyMetadata(new DefaultContentLoader()));
        /// <summary>
        /// Identifies the ListWidth dependency property.
        /// </summary>
        public static readonly DependencyProperty ListWidthProperty = DependencyProperty.Register("ListWidth", typeof(GridLength), typeof(ModernVerticalMenu), new PropertyMetadata(new GridLength(170)));
        /// <summary>
        /// Identifies the Links dependency property.
        /// </summary>
        public static readonly DependencyProperty LinksProperty = DependencyProperty.Register("Links", typeof(LinkCollection), typeof(ModernVerticalMenu), new PropertyMetadata(OnLinksChanged));
        /// <summary>
        /// Identifies the SelectedSource dependency property.
        /// </summary>
        public static readonly DependencyProperty SelectedSourceProperty = DependencyProperty.Register("SelectedSource", typeof(Uri), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedSourceChanged));
        /// <summary>
        /// Defines the SelectedLinkGroup dependency property.
        /// </summary>
        public static readonly DependencyProperty SelectedLinkGroupProperty = DependencyProperty.Register("SelectedLinkGroup", typeof(LinkCollection), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedLinkGroupChanged));
        /// <summary>
        /// Defines the SelectedLink dependency property.
        /// </summary>
        public static readonly DependencyProperty SelectedLinkProperty = DependencyProperty.Register("SelectedLink", typeof(Link), typeof(ModernVerticalMenu), new PropertyMetadata(OnSelectedLinkChanged));
        /// <summary>
        /// Defines the SelectedLink dependency property.
        /// </summary>
        public static readonly DependencyProperty BackColorProperty = DependencyProperty.Register("BackColor", typeof(SolidColorBrush), typeof(ModernVerticalMenu), new PropertyMetadata(null));


        /// <summary>
        /// Occurs when the selected source has changed.
        /// </summary>
        public event EventHandler<SourceEventArgs> SelectedSourceChanged;

        private ListBox linkList;

        /// <summary>
        /// Initializes a new instance of the <see cref="ModernVerticalMenu"/> control.
        /// </summary>
        public ModernVerticalMenu()
        {
            this.DefaultStyleKey = typeof(ModernVerticalMenu);
            // this.BackColor = new SolidColorBrush(Color.FromRgb(0,0,255));

            // create a default links collection
            SetCurrentValue(LinksProperty, new LinkCollection());
        }

        private static void OnSelectedLinkGroupChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            // retrieve the selected link from the group
            var group = (LinkCollection)e.NewValue; // cria uma nova instancia do grupo
            Link selectedLink = null; //cria um link selecionado
              if (group != null)
              { //se o grupo copiado existe

                  selectedLink = group.FirstOrDefault();

              }

              // update the selected link
              ((ModernVerticalMenu)o).SetCurrentValue(SelectedLinkProperty, selectedLink);
        }

        private static void OnSelectedLinkChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            // update selected source
            var newValue = (Link)e.NewValue;
            Uri selectedSource = null;
            if (newValue != null)
            {
                selectedSource = newValue.Source;
            }
            ((ModernVerticalMenu)o).SetCurrentValue(SelectedSourceProperty, selectedSource);
        }


        private static void OnLinksChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ModernVerticalMenu)o).UpdateSelection();
        }

        private static void OnSelectedSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ModernVerticalMenu)o).OnSelectedSourceChanged((Uri)e.OldValue, (Uri)e.NewValue);
        }

        private void OnSelectedSourceChanged(Uri oldValue, Uri newValue)
        {
            UpdateSelection();

            // raise SelectedSourceChanged event
            var handler = this.SelectedSourceChanged;
            if (handler != null) {
                handler(this, new SourceEventArgs(newValue));
            }
        }

        private void UpdateSelection()
        {
            if (this.linkList == null || this.Links == null) {
                return;
            }

            // sync list selection with current source
            this.linkList.SelectedItem = this.Links.FirstOrDefault(l => l.Source == this.SelectedSource);
           // SetValue(SelectedLinkGroupProperty, this.Links.FirstOrDefault(l => l.Children == this.SelectedLinkGroup));
            if (this.Links.FirstOrDefault(l => l.Children == this.SelectedLinkGroup) != null) { }

        }

        /// <summary>
        /// When overridden in a derived class, is invoked whenever application code or internal processes call System.Windows.FrameworkElement.ApplyTemplate().
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (this.linkList != null) {
                this.linkList.SelectionChanged -= OnLinkListSelectionChanged;
            }

            this.linkList = GetTemplateChild("LinkList") as ListBox;
            if (this.linkList != null) {
                this.linkList.SelectionChanged += OnLinkListSelectionChanged;
            }

            UpdateSelection();
        }

        private void OnLinkListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //
            var link = this.linkList.SelectedItem as Link;
            if (link != null && link.Source != this.SelectedSource)
            {
                SetCurrentValue(SelectedSourceProperty, link.Source);

                SetCurrentValue(SelectedLinkGroupProperty, link.Children);
            }
        }

        /// <summary>
        /// Gets or sets the content loader.
        /// </summary>
        public IContentLoader ContentLoader
        {
            get { return (IContentLoader)GetValue(ContentLoaderProperty); }
            set { SetValue(ContentLoaderProperty, value); }
        }

        /// <summary>
        /// Gets or sets the collection of links that define the available content in this tab.
        /// </summary>
        public LinkCollection Links
        {
            get { return (LinkCollection)GetValue(LinksProperty); }
            set { SetValue(LinksProperty, value); }
        }

        /// <summary>
        /// Gets or sets the collection of links that define the available content in this tab.
        /// </summary>
        public LinkCollection SelectedLinkGroup
        {
            get { return (LinkCollection)GetValue(SelectedLinkGroupProperty); }
            set { SetValue(SelectedLinkGroupProperty, value); }
        }

        /// <summary>
        /// Gets or sets the collection of links that define the available content in this tab.
        /// </summary>
        public Link SelectedLink
        {
            get { return (Link)GetValue(SelectedLinkProperty); }
            set { SetValue(SelectedLinkProperty, value); }
        }

        /// <summary>
        /// Gets or sets the width of the list when Layout is set to List.
        /// </summary>
        /// <value>
        /// The width of the list.
        /// </value>
        public GridLength ListWidth
        {
            get { return (GridLength)GetValue(ListWidthProperty); }
            set { SetValue(ListWidthProperty, value); }
        }

        /// <summary>
        /// Gets or sets the source URI of the selected link.
        /// </summary>
        /// <value>The source URI of the selected link.</value>
        public Uri SelectedSource
        {
            get { return (Uri)GetValue(SelectedSourceProperty); }
            set { SetValue(SelectedSourceProperty, value); }
        }

        /// <summary>
        /// Gets or sets the source URI of the selected link.
        /// </summary>
        /// <value>The source URI of the selected link.</value>
        public SolidColorBrush BackColor
        {
            get { return (SolidColorBrush)GetValue(BackColorProperty); }
            set { SetValue(BackColorProperty, value); }
        }
    }
}

From my understanding of the code, you are trying to set the SelectedLinkGroup property to the items in your LinkList when your mouse is over a ListBoxItem. 根据我对代码的理解,当鼠标悬停在ListBoxItem上时,您正在尝试将SelectedLinkGroup属性设置为LinkList中的项目。

As your LinkList's ItemsSource is bound to the Links property on your control you should be able to bind directly to this property to obtain the same result. 由于LinkList的ItemsSource已绑定到控件上的Links属性,因此您应该能够直接绑定到此属性以获得相同的结果。 The following code does just that. 下面的代码就是这样做的。

Value="{Binding Links, RelativeSource={RelativeSource TemplatedParent}}"

Alternatively you could bind to the LinkList Items directly. 或者,您可以直接绑定到LinkList项目。

Value="{Binding ElementName=LinkList,  Path=ItemsSource}"

Here you specify the name of the element to bind to and the property on that element. 在这里,您可以指定要绑定的元素的名称以及该元素的属性。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM