使用按钮更改模板,无需代码

时间:2012-10-15 15:20:32

标签: wpf xaml

我有一个带有Listview的XAML代码。现在我想用一个按钮更改CellTemplate 但没有代码。我怎么能这样做?

模板:

<DataTemplate x:Key="URL"  >
  <TextBlock>
    <Hyperlink NavigateUri="{Binding XPath=@URL}">
      <TextBlock Text="{Binding XPath=@URL}"/>
    </Hyperlink>
  </TextBlock>
</DataTemplate>

<DataTemplate x:Key="Text">
  <TextBlock Text="{Binding XPath=@URL}"/>
</DataTemplate>    


<Grid>  
<Grid.Resources>
  <XmlDataProvider x:Key="Data">
    <x:XData>
      <Data xmlns="">
        <Item ID="1" Desc="Google" URL="http://www.google.com" Acceptable="true"/>
        <Item ID="2" Desc="StackOverflow" URL="http://www.stackoverflow.com" Acceptable="true"/>
        <Item ID="3" Desc="4chan" URL="http://www.4chan.org" Acceptable="false"/>
      </Data>
    </x:XData>
  </XmlDataProvider>
</Grid.Resources>
<Grid.ColumnDefinitions>
  <ColumnDefinition Width="100"/>
  <ColumnDefinition Width="300"/>
</Grid.ColumnDefinitions>

这是魔法应该发生的按钮,并从URLColumn设置CellTemplate。 我想点击这个按钮时将Text作为CellTemplate。

<Button Grid.Column="0" 
  Name="Text"
  Content="Text"/>

使用GridViewColumn URLColumn的Listview。我想改变它的CellTemplate。

<ListView 
  Grid.Column="1"
  DataContext="{Binding Source={StaticResource Data}, XPath=/Data}"
  ItemsSource="{Binding XPath=Item}">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="ID" DisplayMemberBinding="{Binding XPath=@ID}"/>
      <GridViewColumn Header="Description" DisplayMemberBinding="{Binding XPath=@Desc}"/>
      <GridViewColumn x:Key="URLColumn" Header="URL" CellTemplate="{StaticResource URL}"/>
      <GridViewColumn Header="Acceptable">
        <GridViewColumn.CellTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding XPath=@Acceptable}"/>
          </DataTemplate>
        </GridViewColumn.CellTemplate>
      </GridViewColumn>
    </GridView>
  </ListView.View>
  </ListView>

这可能没有代码吗?如果是这样,怎么样? 我已经整天都在网上搜索,但找不到一个回答。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

首先安装Expression Blend Interactivity NuGet包(或手动添加Expression Blend SDK对Microsoft.Expression.Interactions.dll的引用):

Install-Package Blend.Interactivity.Wpf

然后使用ChangePropertyAction触发操作:

<Button
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ic="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions" Grid.Column="0" Name="Text" Content="Text">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <ic:ChangePropertyAction TargetName="URLColumn" PropertyName="CellTemplate" Value="{StaticResource Text}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>
相关问题