[英]WPF: set trigger binding in code behind
我使用帶有圖標的矩形來顯示計算狀態。 我定義了一個帶有數據觸發器和綁定“ IsCompleted”的樣式來處理計算狀態(完成/失敗=未完成)。 我現在有一個以上的計算,並希望使用相同類型的矩形(所有樣式和行為都相同)進行多個計算。 我知道通常如何為一個矩形設置IsCompleted的綁定。
如何在特定矩形后面的代碼中設置觸發器的綁定(例如,calculation1.iconStyle.IsCompleted = true)? 這是否可能,或者我必須為每次計算定義一種樣式(這會帶來很多額外的代碼)?
xaml:
<VisualBrush x:Key="NotCompleted" Stretch="Fill" Visual="{StaticResource appbar_error}" />
<VisualBrush x:Key="Completed" Stretch="Fill" Visual="{StaticResource appbar_check}" />
<Style x:Key="iconStyle" TargetType="{x:Type Rectangle}">
<Setter Property="Width" Value="20"/>
<Setter Property="Fill" Value="Red"/>
<Setter Property="Height" Value="20"/>
<Setter Property="Margin" Value="0,0,5,0"/>
<Setter Property="OpacityMask" Value="{StaticResource NotCompleted}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsCompleted}" Value="True">
<Setter Property="Fill" Value="Green"/>
<Setter Property="OpacityMask" Value ="{StaticResource Completed}"/>
</DataTrigger>
</Style.Triggers>
</Style>
呼叫:
<Rectangle Name="computation1" Style="{StaticResource iconStyle}" Grid.Column="0" VerticalAlignment="Top" />
后面的代碼:
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private bool _isCompleted;
public bool IsCompleted
{
get { return _isCompleted; }
set { _isCompleted= value; NotifyPropertyChanged("IsCompleted"); }
}
private bool comp1(){
....
IsCompleted = !IsCompleted;
}
編輯:
示例輸出:
groupbox1:
| -------------------------
| 計算1:(TextBlock)
| 已完成或未完成的圖標(矩形)
| 均值:(TextBlock)
| 其他一些東西:
| -------------------------
groupbox2:
| -------------------------
| 計算2:(TextBlock)
| 已完成或未完成的圖標(矩形)
| 圖:(圖片)
| 其他一些東西:
| -------------------------
如果必須可視化多個計算的狀態,則應該有一個ItemsControls,它綁定到計算數據項的集合。
<ItemsControl ItemsSource="{Binding Computations}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Style="{StaticResource iconStyle}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
計算項目類可能如下所示:
public class Computation : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool isCompleted;
public bool IsCompleted
{
get { return isCompleted; }
set
{
isCompleted = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("IsCompleted"));
}
}
}
}
並可以像這樣在您的MainWindow類中使用:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Computations = new ObservableCollection<Computation>();
Computations.Add(new Computation());
Computations.Add(new Computation());
Computations.Add(new Computation());
DataContext = this;
Computations[1].IsCompleted = true;
}
public ObservableCollection<Computation> Computations { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.