ItemSource не обновляется при использовании свойства зависимостей ObservableCollection - PullRequest
0 голосов
/ 22 января 2020

У меня есть собственный Ribboncontrol (производный от Selector), в котором есть вкладки и панели (панели, добавленные внутри вкладок) (оба получены из ItemsControl), но я пытаюсь добавить новый режим, который называется упрощенным, где бары могут быть определены в новом Свойство Tab называется SimplifiedItems, которое является наблюдаемой коллекцией, поэтому теперь я могу добавлять столбцы как в Tab.Items, так и в Tab.SimplifiedItems. Чтобы заполнить бары, в xaml я использую ItemsControl, а ресурс источника будет задан как SelectedTab.Items (SelectedTab - свойство Ribboncontrol) в обычном режиме, но в новом упрощенном режиме я устанавливаю как SelectedTab.SimplifiedItems,

Теперь я определил упрощенные элементы для всех моих 4 вкладок и, когда я бегу, я заметил все упрощенные элементы, определенные на всех вкладках, отображаемых под первой вкладкой, и такие же, когда выбраны другие вкладки, я не могу понять, в чем проблема, но мне нужно отобразить соответствующие упрощенные элементы для выбранной вкладки.

Вот код. Шаблон Xaml

                   <Border x:Name="ribBorder"
                        Grid.Row="1"
                        Margin="0,-1,0,0"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="0,1,0,1"
                        Padding="0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <local:RibbonTabItemsControl x:Name="ribbonTabItemsControl" DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                                 Path=SelectedTabItem.DisplayMemberPath}"
                                                     Focusable="False"
                                                     ItemContainerStyle="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                                  Path=SelectedTabItem.ItemContainerStyle}"
                                                     ItemContainerStyleSelector="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                                          Path=SelectedTabItem.ItemContainerStyleSelector}"
                                                     ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                           Path=SelectedTabItem.Items}"
                                                     ItemStringFormat="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                                Path=SelectedTabItem.ItemStringFormat}"
                                                     ItemTemplate="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                            Path=SelectedTabItem.ItemTemplate}"
                                                     ItemTemplateSelector="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                                    Path=SelectedTabItem.ItemTemplateSelector}">


                        </local:RibbonTabItemsControl>

                        </Grid>
                    </Grid>
                </Border>

            </Grid>
        </Border>
    </AdornerDecorator>
    <ControlTemplate.Triggers>
        <Trigger Property="IsSimplified" Value="True">
            <Setter TargetName="ribbonTabItemsControl" Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource TemplatedParent},
                                                                           Path=SelectedTabItem.SimplifiedItems}"/>
        </Trigger>

В Xaml вы можете видеть, что есть триггер для изменения ItemsSource для упрощенного режима.

Свойство SimplifiedItems в классе вкладок:

    public ObservableCollection<Control> SimplifiedItems
    {
        get { return (ObservableCollection<Control>)GetValue(SimplifiedItemsProperty); }
        set { SetValue(SimplifiedItemsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SimplifiedItems.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SimplifiedItemsProperty =
        DependencyProperty.Register("SimplifiedItems", typeof(ObservableCollection<Control>), typeof(Tab), new PropertyMetadata(new ObservableCollection<Control>()));

Пример уровень: это простой код, демонстрирующий, как я использую его в примере, где у меня есть вкладки, а каждая вкладка имеет коллекцию упрощенных элементов.

 <local:Tab Caption="Home" IsChecked="True">
        <local:Tab.SimplifiedItems>
            <local:Bar x:Name="test"
                                      CollapseImage="/Resources/Paste32.png"
                                      Header="Clipboard">
                <Button Content="Button1">

                </Button>
                <Button Content="Button1">

                </Button>
                <Button Content="Button1">

                </Button>

            </local:Bar>

        </local:Tab.SimplifiedItems>
        <local:Bar Name="format_barClipboaurd" 
                                      CollapseImage="/Resources/Paste32.png"
                                      Header="Clipboard">
            <Button Content="Button">

            </Button>
        </local:Bar>

    </local:Tab>

    <local:Tab Caption="New" >
        <local:Tab.SimplifiedItems>
            <local:Bar x:Name="test1"
                                      Header="New">
                <Button Content="Button1">

                </Button>
                <Button Content="Button1">

                </Button>
                <Button Content="Button1">

                </Button>

            </local:Bar>

        </local:Tab.SimplifiedItems>
        <local:Bar Name="format_barClipboaurd" 
                                      Header="New">
            <Button Content="Button">

            </Button>
        </local:Bar>

    </local:Tab>
</Grid>

Редактировать: я подготовил простой пример для воспроизведения проблемы, в следующем примере у меня есть TabControl, а внутри у меня есть TabItemExt (локальный класс), и у него есть коллекция SimplifiedItems, которая является ObservableCollection, в представлении у меня есть другой ItemSource, который я связал с TabItemExt.SimplifiedItems в коде позади, но когда я запускаю образец, все три упрощенных определяются в трех элементах, где показаны вместе.

Пример здесь

Пожалуйста, дайте мне знать, если у вас есть какие-либо вопросы или если вам нужна дополнительная информация. Заранее спасибо.

1 Ответ

0 голосов
/ 27 января 2020

Я решил проблему, изменив значение по умолчанию SimplifiedItems на null, а затем инициализировав новый экземпляр в конструкторе Tab как stati c, метод SimplifiedItemsProperty для stati c (или singleton) ObservableCollection будет создан.

public class TabItemExt : ItemsControl
{
    public TabItemExt() => SimplifiedItems = new ObservableCollection<Control>();

    public string Header
    {
      get { return (string)GetValue(HeaderProperty); }
      set { SetValue(HeaderProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Header.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("Header", typeof(string), typeof(TabItemExt), new PropertyMetadata(String.Empty));

    public ObservableCollection<Control> SimplifiedItems
    {
      get { return (ObservableCollection<Control>)GetValue(SimplifiedItemsProperty); }
      set { SetValue(SimplifiedItemsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SimplifiedItems.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SimplifiedItemsProperty =
        DependencyProperty.Register("SimplifiedItems", typeof(ObservableCollection<Control>), typeof(TabItemExt), new PropertyMetadata(null));
}
...