问题描述
我有一个 ObservableCollection
为 ItemSource
的 ListBox:
public partial class HomePage : Page
{
public ObservableCollection<DaemonFile> Files { get; private set; }
private readonly MainWindow MainWindow;
public HomePage(MainWindow MainWindow)
{
Files = new ObservableCollection<DaemonFile>();
this.MainWindow = MainWindow;
InitializeComponent();
listofFiles.ItemsSource = Files;
}
...
}
我的 DaemonFile
中有以下属性:
public class DaemonFile : INotifyPropertyChanged
{
public enum Processstates : int
{
CREATED = 0,CONVERTED = 1,UPLOADING = 2,FINISHED = 3
}
private Processstates ProcessstateValue = Processstates.CREATED;
public Processstates Processstate
{
get { return this.ProcessstateValue; }
set
{
if (value != this.ProcessstateValue)
{
this.ProcessstateValue = value;
NotifyPropertyChanged();
}
}
}
...
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
mainWindow.WriteLine("Property " + propertyName + " Changed!");
PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
} else
{
mainWindow.WriteLine("Cant fire event!");
}
}
}
文件转换完成后,Processstate
会异步更新。
我想我需要绑定这个属性并将它放入 IsEnabled
的 setter 中。
<Style x:Key="Item" targettype="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate targettype="{x:Type ListBoxItem}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}">
</ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding Processstate}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
每当 DaemonFile
将其 Processstate
更改为 1 或更高时,相应的 ListBoxItem 切换到启用状态时,我该如何实现?
我还可以将 isEnabled
属性添加到我的 DaemonFile
以稍微简化事情。但这并不能解决我的绑定问题。
解决方法
您不需要那个 ControlTemplate。
一个简单的 DataTrigger 应该可以工作:
<Style x:Key="ItemStyle" TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding ProcessState}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Trigers>
</Style>
以防万一:
<ListBox x:Name="ListOfFiles"
ItemContainerStyle="{StaticResource ItemStyle}" ...>