WPF Xaml передает управление в атрибут - PullRequest
0 голосов
/ 21 июля 2011

У меня есть TextBox (называемый SearchBox) и ListView (называемый EmployeeList). Событие TextChanged TextBox отображает результаты поиска в ListView. Все это работает хорошо, но мне нужны дополнительные функции, я хочу захватывать события KeyUp / Down для навигации по элементам ListView. Я знаю, что могу просто добавить обработчик к событиям KeyUp / Down и закончить, но это то, чем я буду часто пользоваться, поэтому я хотел что-то, что можно использовать повторно.

Вот что я пытался сделать, я создал статический класс (называемый SearchBoxHelper) и добавил присоединяемое свойство. Теперь я хочу передать ссылку на элемент управления ListView (не одно из его свойств) в качестве значения для свойства присоединяемой зависимости через xaml.

/ Органы управления / SearchBoxHelper.cs

public static class SearchBoxHelper
{
    public static readonly DependencyProperty HelpsListView = DependencyProperty.RegisterAttached("HelpsListView", typeof(ListView), typeof(SearchBoxHelper), new PropertyMetadata(null, OnHelpsListViewChanged));

    private static void OnHelpsListViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ListView listview = d as ListView;

        // this is where it crashes, because the d is not of type ListView
        MessageBox.Show(listview.Name);
    }

    public static ListView GetHelpsListView(DependencyObject d)
    {
        return d.GetValue(HelpsListView) as ListView;
    }

    public static void SetHelpsListView(DependencyObject d, ListView listview)
    {
        d.SetValue(HelpsListView, listview);
    }

}

/ Страницы / EmployeesPage.xaml

<control:NavPage x:Class="DtcInvoicer.Pages.EmployeesPage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:control="clr-namespace:DtcInvoicer.Controls"
             x:Name="Page" Width="950" Height="580"
             Loaded="Page_Loaded">

    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="350" />
            <ColumnDefinition Width="260" />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0">
            <TextBlock FontSize="22" FontWeight="SemiBold" Text="Employees" />
        </StackPanel>
        <StackPanel Grid.Row="1" Grid.Column="0">
            <control:PolygonContainer Points="0,0 330,0 340,10 350,30 0,30" Background="{StaticResource Gradient_Black}">
                <WrapPanel>
                    <TextBox x:Name="SearchBox" TextChanged="SearchBox_TextChanged" control:SearchBoxHelper.HelpsListView="{x:Reference Name=EmployeeList}" Margin="5" Width="300" Height="20" BorderThickness="0" Background="#30FFFFFF" Foreground="White" />
                    <Image Width="18" Source="/Images/Icons/Search.png" />
                </WrapPanel>
            </control:PolygonContainer>
            <Border Height="490" CornerRadius="0,0,5,5" Background="{StaticResource Gradient_Blue}">
                <StackPanel>
                    <control:FxListView x:Name="EmployeeList" ItemDoubleClick="EmployeeList_ItemDoubleClick"  Height="455" BorderThickness="0" Background="Transparent" ItemContainerStyle="{StaticResource FxListViewItemContainer_Style}" ItemTemplate="{StaticResource Employee_ListViewItem_Template}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
                    <WrapPanel Height="30" />
                </StackPanel>
            </Border>
        </StackPanel>
        <StackPanel Margin="10,0,0,0" Grid.Row="1" Grid.Column="1">
            <control:PolygonContainer Points="250,0 20,0 10,10 0,30 250,30" Background="{StaticResource Gradient_Black}">
                <TextBlock Margin="0,0,5,0" Text="Open Employees" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Center" />
            </control:PolygonContainer>
            <Border Height="180" CornerRadius="0,0,5,5" Background="{StaticResource Gradient_Blue}">
                <control:FxListView x:Name="OpenEmployeesList" ItemDoubleClick="OpenEmployeesList_ItemDoubleClick" Height="160" VerticalAlignment="Top" BorderThickness="0" Background="Transparent" ItemContainerStyle="{StaticResource FxListViewItemContainer_Style}" ItemTemplate="{StaticResource EmployeePage_ListViewItem_Template}" />
            </Border>
        </StackPanel>
    </Grid>
</control:NavPage>

1 Ответ

0 голосов
/ 21 июля 2011

Разобрался ... для всех, кому это может понадобиться ..

private static void OnHelpsListViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // ListView listview = d as ListView;

    // the propblem was with the line above, I was trying to convert the 
    // DependencyObject to a ListView and it's actually a TextBox, I should 
    // have been converting the new value of the DependencyProperty

    TextBox box = d as TextBox;
    ListView list = e.NewValue as ListView;
    if(box == null || list == null) return;

    box.PreviewKeyDown += delegate(object sender, KeyEventArgs e2)
    {
        if (e2.Key == Key.Down)
            list.SelectedIndex += (list.SelectedIndex + 1 < list.Items.Count) ? 1 : 0;
        else if (e2.Key == Key.Up)
            list.SelectedIndex -= (list.SelectedIndex - 1 >= 0) ? 1 : 0;
        else if (e2.Key == Key.Enter && list.SelectedIndex >= 0)
        { 
            // do something for the enter key 
        }
    };
}
...