您可以創建一個轉換器並使用轉換器參數進行處理。請參閱以下代碼。同意@Sam,但如果他有更多的地位,那麼下面的代碼將有所幫助。
<Window x:Class="DataGrid_Status.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGrid_Status"
mc:Ignorable="d"
Title="Window4" Height="300" Width="300">
<Grid>
<Grid.Resources>
<local:StatusConverter x:Key="StatusConverter"></local:StatusConverter>
</Grid.Resources>
<DataGrid x:Name="DataGrid" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Fungsi" Width="150" IsReadOnly="True" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Name="btn1" Content="Success" Background="Green"
Visibility="{Binding Status,Converter={StaticResource StatusConverter},ConverterParameter=a}"></Button>
<Button Name="btn2" Content="InProg" Background="Yellow"
Visibility="{Binding Status,Converter={StaticResource StatusConverter},ConverterParameter=b}"></Button>
<Button Name="btn3" Content="Failed" Background="Red"
Visibility="{Binding Status,Converter={StaticResource StatusConverter},ConverterParameter=c}"></Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace DataGrid_Status
{
/// <summary>
/// Interaction logic for Window4.xaml
/// </summary>
public partial class Window4 : Window
{
public Window4()
{
InitializeComponent();
List<MyClass> lst = new List<MyClass>();
for (int i = 0; i < 10; i++)
{
MyClass obj = new MyClass();
obj.Name = "Name" + i;
if (i == 1)
{
obj.Status=StatusEnum.Success;
}
else if (i == 2)
{
obj.Status = StatusEnum.Failed;
}
else
{
obj.Status = StatusEnum.InProgress;
}
lst.Add(obj);
}
DataGrid.ItemsSource = lst;
}
}
class StatusConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
StatusEnum status = (StatusEnum)value;
string param = parameter as string;
if ((status == StatusEnum.Success && param == "a")|| (status == StatusEnum.InProgress && param == "b")|| (status == StatusEnum.Failed && param == "c"))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
class MyClass
{
public string Name { get; set; }
public StatusEnum Status { get; set; }
}
enum StatusEnum
{
Success,
Failed,
InProgress
}
}
你能轉換器添加到資源和狀態綁定到按鈕的知名度.. –