【发布时间】:2015-02-09 22:50:07
【问题描述】:
目前在我的列表视图中,我正在使用如下代码设置文本、图片和文本颜色 - http://oi61.tinypic.com/nzggls.jpg
foreach (Mods modname in gameMods)
{
if (Directory.Exists(Path.Combine(ArmA3PATH, "@" + modname.ModString)))
{
lstMods.Items.Add(new listViewItem
(
modname.ModName.ToString(),
Path.Combine(dir, modname.ModLink),
new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Green)
)
);
}
else
{
lstMods.Items.Add(new listViewItem
(
modname.ModName.ToString(),
Path.Combine(dir, modname.ModLink),
new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red)
)
);
}
}
两个类如下,其中gameMods只是一个用Mods创建的List,List
public class listViewItem
{
public string Text { get; set; }
public string ImagePic { get; set; }
public System.Windows.Media.SolidColorBrush BackgroundColor { get; set; }
public listViewItem(string text, string image, System.Windows.Media.SolidColorBrush color)
{
Text = text;
ImagePic = image;
BackgroundColor = color;
}
}
public class Mods
{
public string ModName { get; set; }
public string ModVersion { get; set; }
public string ModLink { get; set; }
public string ModString { get; set; }
public string ModLogo { get; set; }
public Mods(string modName, string modVersion, string modLink, string modString, string modLogo)
{
this.ModName = modName;
this.ModVersion = modVersion;
this.ModLink = modLink;
this.ModString = modString;
this.ModLogo = modLogo;
}
}
上述代码的 XAML 标记是
<ListView x:Name="lstMods">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Image Source="{Binding ImagePic}" Width="80" Height="80" Stretch="Fill"/>
<TextBlock Name="txtBlock" Text="{Binding Text}" Foreground="{Binding BackgroundColor}" VerticalAlignment="Center" TextAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Width="{Binding (FrameworkElement.ActualWidth),
RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}"
ItemWidth="248"
MinWidth="{Binding ItemWidth, RelativeSource={RelativeSource Self}}"
ItemHeight="{Binding (ListView.View).ItemHeight,
RelativeSource={RelativeSource AncestorType=ListView}}" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
现在,这很好用;但是我不能像这样使用 SelectionChanged 和 SelectedItem 来获取值,那么我可以通过什么方式在 ListView 上使用 ItemsSource 并仍然将图像/文本添加到 ListView 块中?
目前在做 lstMods.ItemsSource = gameMods 时的 ItemsSource 是这样的http://oi59.tinypic.com/dwi0m.jpg
我知道这是因为没有绑定文本值,但我不太确定在哪里为 Item Sourcing 添加这些值。
【问题讨论】:
-
你正在使用 WPF 人!只需将 SelectedItem 作为属性绑定到,只要您实现 INotifyPropertyChanged,您就可以订阅更改。如果您创建 ObservableCollection
(与在 .Net 中声明 List 的方式相同),您可以添加和删除 mods,并且更改将直观地反映在 ListView 上。为您当前选择的一个 Mod 属性创建一个。 -
我想引用的不是更改,它们都是通过 XML 文件处理的,供服务器管理员更新或修改;它更多的是通过 ItemsSource 填充列表以将 gameList 信息附加到该 ListView 项目,以便您可以检索有关您选择的项目的信息。去看看一些 MSDN 文章,看看我可以用它为 SelectedItem 或 ItemsSource & SelectionChanged 做什么
标签: c# wpf listview visual-studio-2013