【问题标题】:Set default value to dynamically bind-generated controls将默认值设置为动态绑定生成的控件
【发布时间】:2013-08-27 23:38:58
【问题描述】:

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

我已经为控件创建了这个 DependencyProperty(一个单选按钮组,它将字典(键:字符串值:位图)作为 ItemSource 并创建单选按钮和相应的图像)。

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"/>

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    好的,我设法像这样修复它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2018-12-30
      • 2012-02-23
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多