Access UniformGrid ItemTemplate programmatically

2019-06-06 01:32发布

问题:

I'm trying to build a bingo game simulator using WPF to learn more about WPF, and I'm having trouble figuring out how to change an <ItemsControl> template programmatically.

I'm only using the default WPF Application from VS 2010, so I have a MainWindow.xaml, App.xaml and MainWindow.xaml.cs.

The reason I want to access the <ItemTemplate>, is to change the bound template if that bingo number comes up as chosen.

I've tried this possible solution in my code behind file, but I don't think that works in this situation.

Here is how I have my MainWindow and App xaml files set up

MainWindow.xaml

<ItemsControl Name="icBColumn" ItemsSource="{Binding CardBNumbers}" 
              Grid.Column="0" Grid.Row="2" 
              ItemTemplate="{StaticResource BingoSquare}"
              ItemsPanel="{StaticResource BingoColumn}">

App.xaml

<DataTemplate x:Key="BingoSquare">
  <Border Background="{DynamicResource UnmarkedSquare}">
    <Label Content="{Binding}" />
  </Border>
</DataTemplate>
<RadialGradientBrush x:Key="UnmarkedSquare" GradientOrigin="0.5,0.5" 
                     Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
  <RadialGradientBrush.GradientStops>
    <GradientStop Color="LimeGreen" Offset="1" />
  </RadialGradientBrush.GradientStops>
</RadialGradientBrush>
<ItemsPanelTemplate x:Key="BingoColumn">
  <UniformGrid Name="NumbersGrid" Columns="1" Rows="5"/>
</ItemsPanelTemplate>

回答1:

Check this link there you will find code that is close enough to what you need but needs some work.

I would propose some recontruction.

For example you bind your ItemsControl's ItemsSource to CardBNumbers. Is it a list of int or a list of CustomClass e.g. BingoNumClass. If it is a custom class the add a boolean IsBingo boolean property which you will by defualt turn to false. It will turn to true from your code whenever a bingo number is selected and you will update the items of CardBNumbers list.

Then you could extend your ItemTemplate with Datatriggers on IsBingo Property to Chnage its appearrence as soon as it is selected - turned to true from your CardBNumbers list.