和評論者一樣,我也將這個邏輯放入ViewModel。這是一個例子。我正在使用GalaSoft.MvvmLight nuget包。
查看XAML:
<Window.Resources>
<local:BoolToBrushConverter x:Key="boolToColorConv" />
</Window.Resources>
<Grid>
<ListBox Name="empLB" ItemsSource="{Binding Path=emp}" Height="100" Width="300" VerticalAlignment="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Width="300" >
<TextBox Name="txt2"
Text="{Binding Path= RollNo}"
Background="{Binding Path=DataContext.ContainsItems,
Converter={StaticResource boolToColorConv},
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}} }" />
<TextBox Name="txt1"
Text="{Binding Path=Name}"
Background="{Binding Path=DataContext.ContainsItems,
Converter={StaticResource boolToColorConv},
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}} }" />
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="btnClick" Height="20" Width="100" Content="click On me" Command="{Binding BtnClick}" />
</Grid>
查看代碼:
public partial class RollWindow : Window
{
public RollWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// You might want to replace this with a ViewModel locator
DataContext = new RollsViewModel();
}
}
視圖模型:
public class RollsViewModel : ViewModelBase
{
public ObservableCollection<Item> emp
{
get;
set;
}
public bool ContainsItems
{
get { return _containsItems; }
set { _containsItems = value; RaisePropertyChanged(); }
}
private bool _containsItems;
public RollsViewModel()
{
emp = new ObservableCollection<Item>();
}
public ICommand BtnClick
{
get
{
if (_btnClick == null)
{
_btnClick = new RelayCommand(() =>
{
// Dummy action, replace with call to model
emp.Add(new Item() { Name = "A roll", RollNo = emp.Count });
ContainsItems = emp.Count > 0;
});
}
return _btnClick;
}
}
private RelayCommand _btnClick;
}
public class Item : ViewModelBase
{
public int RollNo
{
get { return _rollNo; }
set { _rollNo = value; RaisePropertyChanged(); }
}
private int _rollNo;
public string Name
{
get { return _name; }
set { _name = value; RaisePropertyChanged(); }
}
private string _name;
}
轉換器:
public class BoolToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = (value is bool && (bool)value) ? System.Windows.Media.Colors.Green : System.Windows.SystemColors.ControlColor;
return new SolidColorBrush(color);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
的EAS y方式只是將背景顏色綁定到字符串變量,並在點擊按鈕'string color =「Green」時更改它' – FakeCaleb
Button不包含Click屬性,因此您在該樣式中的綁定不會產生任何效果。除此之外,如果要更改文本框的背景,應將樣式分配給文本框,而不是按鈕。就像上面說的,在你的視圖模型中有一個屬性,並直接從你的文本框綁定到它。因爲該屬性不會成爲你的列表的一部分,你需要在這裏使用relativesource綁定。 – adminSoftDK