将默认值设置为动态绑定生成的控件

时间:2013-08-26 20:46:08

标签: c# wpf xaml

我无法在用户控件中设置默认的SelectedIndex值。

我为控件创建了这个 DependencyProperty (一个RadioButton组,它将ItemSource作为一个Dictionary(键:字符串值:Bitmap)并创建Radiobuttons和相应的Images)。

public int SelectedIndex
{
    get { return (int)GetValue(SelectedIndexProperty); }
    set { SetValue(SelectedIndexProperty, value); }
}
public static readonly DependencyProperty SelectedIndexProperty = 
    DependencyProperty.Register(
                                "SelectedIndex", 
                                typeof(int), 
                                typeof(RadioGroup), 
                                new FrameworkPropertyMetadata(0, OnSelectedIndexChanged)
                                );
private static void OnSelectedIndexChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    var control = (RadioGroup)source;
    if (control.ItemsSource == null) return; // When assigning SelectedIndex from the XAML the collection it`s not initialized yet
    if (e.NewValue != null)
    {
        var radioButton =(RadioButton)VisualTreeHelper.GetChild((control.container.ItemContainerGenerator.ContainerFromIndex((int) e.NewValue)), 0);
        radioButton.IsChecked = true;
    }
    var x = -1; 
    foreach (var item in control.ItemsSource)// Apparently I cannot convert the IEnumerable to List for this i do this odd loop with the external counter
    {
        x++;
        var radioButton = (RadioButton)VisualTreeHelper.GetChild((control.container.ItemContainerGenerator.ContainerFromIndex(x)), 0);
        if (radioButton.IsChecked != true) continue;
        control.SelectedIndex = x;
        var key = control.container.Items[x].ToString();
        var currItem = (KeyValuePair<string, Bitmap>)item;
        control.GroupIcon = currItem.Value;
        return;
    }
}

这是XAML

<UserControl.Resources>
    <local:DictToStringConverter x:Key="DictToStringConverter"/>
    <DataTemplate DataType="{x:Type ItemsPanelTemplate}" x:Key="ItemPanelDatatemplate">
        <RadioButton Margin="0,0,5,0" Content="{Binding}" GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ItemsControl}, Path=Tag}" Checked="ToggleButton_OnChecked" />
    </DataTemplate>
    <ItemsPanelTemplate x:Key="ItemsPanelTemplate">
        <UniformGrid x:Name="grdLayout" Columns="{Binding Path=Columns, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:RadioGroup}}}"/>
    </ItemsPanelTemplate>

</UserControl.Resources>

<Border x:Name="brdMain">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="txtTitle" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Text=""/>
        <Image x:Name="imgImage" Grid.Column="0" Grid.Row="1" Source="{Binding Path=GroupIcon, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:RadioGroup}}}" VerticalAlignment="Top"/>
        <ItemsControl Grid.Column="1" Grid.Row="1" Name="container" Width="{Binding ElementName=scroll, Path=ViewportWidth}" 
                    ItemsSource="{Binding Path=ItemsSource, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:RadioGroup}},Converter={StaticResource DictToStringConverter}}" 
                    ItemTemplate="{StaticResource ItemPanelDatatemplate}" 
                    ItemsPanel="{StaticResource ItemsPanelTemplate}"
        />
    </Grid>
</Border>

如果我单击一个RadioButton,或者如果我从后面的代码中分配属性,那么它的工作原理(图标也正常切换),  问题是在XAML中我指定 SelectedIndex ,但显然绑定发生在之后,因此默认情况下没有选择RadioButton。

<cust:RadioGroup GroupTitle="Symmetry Axis" ItemsSource="{Binding SymmetryAxis}" Columns="3" ItemSelected="RadioGroup_OnSelected" SelectedIndex="2"/>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

好的,我设法解决了这个问题:

   public RadioGroup()
    {
        InitializeComponent();
        Loaded += RadioGroup_Loaded;
    }

void RadioGroup_Loaded(object sender, RoutedEventArgs e)
{
    ((RadioButton)VisualTreeHelper.GetChild((container.ItemContainerGenerator.ContainerFromIndex(SelectedIndex)), 0)).IsChecked = true;
}