WPF C#以编程方式在foreach循环中向DataGrid添加按钮

时间:2015-03-30 09:04:11

标签: c# wpf foreach datagrid wpf-controls

我正在尝试向WPF应用程序中的foreach循环DataGrid添加更多控件。使用下面的代码可以工作,但需要为每个项目添加一个带有click事件的按钮(从xml文件生成)

   foreach (var item in items.Descendants("item"))
   {

    string server_name = item.Element("server_name").Value;
    string server_steam_url = item.Element("server_steam_url").Value;

    servers.Add(new Servers { ServerName = server_name, ServerSteamUrl = server_steam_url, });
    }

   return servers;
    }

下面的xaml文件

<UserControl x:Class="FirstFloor.ModernUI.App.Content.ServersGrid"
         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:core="clr-namespace:System;assembly=mscorlib"
         xmlns:local="clr-namespace:FirstFloor.ModernUI.App.Content"
         xmlns:mui="http://firstfloorsoftware.com/ModernUI"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <DockPanel>
        <TextBlock DockPanel.Dock="Top" Text="Server List" Style="{StaticResource Heading2}" Margin="0,0,0,8" />
        <DataGrid Name="SERVERSDATAGRID" ItemsSource="{Binding}" AutoGenerateColumns="False" MaxWidth="2560" MaxHeight="800" EnableColumnVirtualization = "true" EnableRowVirtualization = "true"  >
            <DataGrid.Columns>
                <mui:DataGridTextColumn Header="Server Name"  Binding="{Binding ServerName,IsAsync=True}"/>
                <DataGridHyperlinkColumn Header="Launch" Binding="{Binding ServerSteamUrl,IsAsync=True}" />
                <DataGridTemplateColumn Header="Launch">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Play" Name="Launch" Click="Launch_Click" Cursor="Hand" ToolTip="Launch Server" Tag="{x:Null}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

            </DataGrid.Columns>
        </DataGrid>
    </DockPanel>
</Grid>

xml文件内容

<?xml version="1.0"?><catalog>
<item>
<server_id>16638</server_id>
<server_name><![CDATA[Dawn of Dayz|God Traders|Custom Ai missions|auto refuel| Towing]]></server_name>
<server_steam_url><![CDATA[steam://run/-mod=ayZ Epoch 1.0.4.2;@rmod;@bliss;; -connect=192.31.185.202 -port=23323]]></server_steam_url>
</item>
<server_id>17203</server_id>
<server_name><![CDATA[SCHWEYERS ARMA]]></server_name>
<server_steam_url><![CDATA[steam://run/-mod=; -connect=198.2.80.118 -port=2303]]></server_steam_url>
</item>
</catalog>

为了获得更高级的效果,我还想为每个项目和/或可折叠面板添加上下文菜单。

0 个答案:

没有答案