2013-03-26 30 views
-1

我把这个Stackpanel与一个网格,并在网格中的多个按钮,其中包含内容显示。这些项目是按字母顺序排列的,而且我已经手动执行此操作。例如,如果一个游戏的名称是“死亡排”,我不得不浪费时间手动移动每个项目,这样我就可以为新项目腾出空间。这里的问题是,是否有一种方法来组织它,以便我可以在代码之间实现代码并自动调整? 代码的外观: Code Example Image按字母顺序排列网格项目

+0

为什么你是否将你的代码发布为.png? – 2013-03-26 16:49:57

回答

0

不要使用DataGrid来布局的动态内容,而使用与DataTemplatesItemsControl和存储你的数据收集在ViewModel,然后使用数据绑定来显示您的内容。这将允许您更改您的数据收集并适当地更新您的UI。

例子:

一个简单的类,它保持每场比赛的细节:

public class GameViewModel 
{ 
    public string Name { get; set; } 
    public string ImagePath { get; set; } 
} 

你的主视图模型:

public class SortedContentViewModel 
{ 
    public ObservableCollection<GameViewModel> GameList { get; set; } 

    public SortedContentViewModel() 
    { 
     GameList = new ObservableCollection<GameViewModel>() 
     { 
      new GameViewModel() {Name="Brink", ImagePath = @"Resources/brink.png" }, 
      new GameViewModel() {Name="Bulletstorm", ImagePath = @"Resources/bulletstorm.png" } 
     }; 
    } 
} 

和您的XAML:

<UserControl x:Class="Wpf_Playground.Views.SortedContentView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:vm="clr-namespace:Wpf_Playground.ViewModels" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300" 
     DataContext="{DynamicResource ViewModel}"> 
<UserControl.Resources> 
    <vm:SortedContentViewModel x:Key="ViewModel" /> 

    <DataTemplate DataType="{x:Type vm:GameViewModel}"> 
     <Button> 
      <Grid> 
       <Image Source="{Binding ImagePath}" Stretch="Fill" /> 
       <Border Background="#66000000" Height="30" VerticalAlignment="Bottom"> 
        <TextBlock Text="{Binding Name}" Margin="10,-2,10,0" VerticalAlignment="Bottom" /> 
       </Border> 
      </Grid> 
     </Button> 
    </DataTemplate> 
</UserControl.Resources> 
    <Grid> 
     <ItemsControl ItemsSource="{Binding GameList}" > 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <WrapPanel /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
    </ItemsControl> 

    </Grid> 
</UserControl> 
+0

谢谢,我知道你是怎么做的,但似乎没有出现。以下是新代码:[XAML] http://speedcap.net/sharing/files/a0/5d/a05def47065215562e54aad70e59e56f.png [C#] http://speedcap.net/sharing/files/f0/a0/f0a014aa004bc9b38bb8c7de5c219a9e.png 。在XAML之上,我已经把DataContext =“{Binding RelativeSource = {RelativeSource Self}}”,所以它会引用它自己。 – user1953522 2013-03-26 18:41:32

+0

你的'DataContext'绑定不能工作,你的想法。看看你的大窗口,我敢打赌你会看到一个绑定错误。如果你想在后面的代码中做所有的事情,那么在你的XAML中摆脱你的''DataContext = ...“',并且只需在你的窗口构造函数中放置'this.DataContext = this;'。 – 2013-03-26 19:00:43

+0

谢谢。我想它是因为它与表单上的另一个ListView一起工作。 – user1953522 2013-03-26 20:04:04