我試圖在樣式上使用數據觸發器來更改屬性。DataTrigger的值設置爲靜態資源會給出錯誤 - 「在'DataTrigger'正在使用(密封)之後,它無法修改」
在遵守 「Minimal, Complete and Verifiable Example」 的要求......
要重現,首先建立在Visual Studio中WPF應用程序。
內App.xaml.cs:
using System.ComponentModel;
using System.Windows;
namespace Foo{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application, INotifyPropertyChanged {
private bool _clicked;
public bool Clicked {
get { return this._clicked; }
set {
this._clicked = value;
this.PropertyChanged?.Invoke(
this, new PropertyChangedEventArgs("Clicked"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
內MainWindow.xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lib="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:Foo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d" x:Class="Foo.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<lib:Boolean x:Key="True">True</lib:Boolean>
</Window.Resources>
<Grid>
<Button x:Name="button" Click="button_Click">
<Viewbox>
<TextBlock Text="Unclicked">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger
Binding="{Binding
Clicked,
Source={x:Static Application.Current}}"
Value="{StaticResource True}">
<Setter Property="Text" Value="Clicked" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Viewbox>
</Button>
</Grid>
</Window>
的MainWindow.xaml.cs內 -
using System.Windows;
namespace Foo{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e) {
(Application.Current as App).Clicked = !(Application.Current as App).Clicked;
}
}
}
作爲一個邊注意 - 我嘗試將數據觸發器的值設置爲"True"
,並且這也不起作用(觸發器沒有t catch,並且文本不會根據將該屬性設置爲新值而更改)。
那麼,爲什麼數據觸發器沒有捕獲或在這裏工作? (要麼與靜態資源或文字值)?更相關 - 爲什麼我得到這個錯誤? 「在'DataTrigger'正在使用(密封)之後,它不能被修改」錯誤?完成我在這裏要做的事情的正確方法是什麼? (最好還是使用數據觸發器而不是轉換器,因爲我確實需要在兩個值之間切換)。
因此,由文字設置的值(與綁定相對)將取代由setter(或數據觸發器設置器)設置的值並使其失效,這是導致我的錯誤的原因? – Will
確切地說,請參閱鏈接的MSDN文章以獲取詳細信息。 – Clemens
謝謝。 我現在沒有時間測試,但我會明天,如果它有效,我會標記你的答案是正確的。 – Will