【问题标题】:WPF: Is it possible to convert the following code from Procedural (C#) to Declarative (XAML)?WPF:是否可以将以下代码从程序 (C#) 转换为声明性 (XAML)?
【发布时间】:2009-05-16 14:27:15
【问题描述】:

我在Window 中有以下内容(删除了不必要的部分):

XAML:

<Style x:Key="itemstyle" TargetType="{x:Type ContentPresenter}">
        <EventSetter Event="MouseLeftButtonDown" Handler="HandleItemClick"/>
</Style>

<ItemsControl ItemsSource="{Binding ArtistList}" Margin="10" Name="artist_list" ItemContainerStyle="{StaticResource itemstyle}" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <TextBlock Text="{Binding ID}" Foreground="White"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

<Controls:RSSViewer x:Name="rssControl" />

C#(背后的代码):

private void HandleItemClick(object sender, MouseButtonEventArgs e)
{
    var selectedArtist = ((ContentPresenter) sender).Content as Artist;
    rssControl.SourceUrl = "http://agnt666laptop:28666/rss.aspx?artistid=" + selectedArtist.ID;
}

现在我想做的是将上述 xaml 和 C# 的混合转换为纯粹的 xaml,以利用 WPF 的 DataBinding 模型。

我认为它需要事件触发器和数据绑定与 itemscontrol 元素的选定项的组合或类似的东西,但我不确定如何去做。

谁能指导我如何转换上述解决方案以删除程序代码?

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    如果您使用的是 .NET 3.5SP1,您可能可以使用新的 StringFormat 绑定标记扩展来执行此操作。请参阅here 了解与 StringFormat 绑定的示例。

    如果 .NET 3.5SP1 不是一个选项,那么您可能必须创建自己的 ValueConverter。将 SourceUrl 属性的值绑定到所选艺术家的 ID,然后在您的转换器中返回您在上面的 C# 示例中使用的相同字符串。

    【讨论】:

      【解决方案2】:
      <ItemsControl ItemsSource="{Binding ArtistList}" Margin="10" Name="artist_list" ItemContainerStyle="{StaticResource itemstyle}" >
              <ItemsControl.ItemTemplate>
                      <DataTemplate>
                                      <TextBlock Text="{Binding ID}" Foreground="White"/>
                      </DataTemplate>
              </ItemsControl.ItemTemplate>
      </ItemsControl>
      
      <Controls:RSSViewer x:Name="rssControl" SourceUrl="{Binding SelectedItem.ID, ElementName=artist_list, StringFormat= 'http://agnt666laptop:28666/rss.aspx?artistid={0}' }" />
      

      【讨论】:

      • 它不起作用:System.Windows.Data 错误:4:找不到与引用“ElementName=artist_list”进行绑定的源。 BindingExpression:Path=SelectedItem.ID;数据项=空;目标元素是“RSSViewer”(名称=“rssControl”);目标属性是'SourceUrl'(类型'String')
      • 我认为 ItemsControl 没有 SelectedItems 属性。如果要选择,则需要使用 ListBox 或 ListView。
      • 安迪说得对,ItemsControl 没有 SelectedItem 属性...所以我们必须用另一种方式来做
      • 是的,没错……你可以使用 Selector 代替 ItemsControl
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多