这是使用 multibinding 的解决方案:
xml:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication8="clr-namespace:WpfApplication8"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<WpfApplication8:ButtonVisibilityConverter x:Key="buttonVisibilityConverter"/>
</Window.Resources>
<DataGrid x:Name="dataGrid" SelectedItem="{Binding MySelectedItem}" ItemsSource="{Binding MyObjectList}" SelectionMode="Single">
<DataGrid.Columns>
<DataGridTemplateColumn Header="H." Width="50">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button
Height="20"
Width="25">
<Button.Visibility>
<MultiBinding Converter="{StaticResource buttonVisibilityConverter}">
<Binding Path="Parent.MySelectedItem"/>
<Binding></Binding>
</MultiBinding>
</Button.Visibility>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
后面的代码:
namespace WpfApplication8
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public class Toto
{
public object Parent { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public Toto(string name, string content, object parent)
{
this.Name = name; this.Content = content; this.Parent = parent;
}
}
private object _mySelectedItem;
public object MySelectedItem
{
get { return _mySelectedItem; }
set
{
_mySelectedItem = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("MySelectedItem"));
}
}
}
private List<Toto> _myObjectList;
public List<Toto> MyObjectList
{
get { return _myObjectList; }
set { _myObjectList = value; }
}
public MainWindow()
{
this.MyObjectList = new List<Toto>
{
new Toto("toto1", "content toto1", this),
new Toto("toto2", "content toto2", this)
};
InitializeComponent();
this.DataContext = this;
}
}
}
转换器:
class ButtonVisibilityConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] == values[1])
{
return Visibility.Visible;
}
else
{
return Visibility.Hidden;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}