2
我在使用DataTrigger操作控件的IsEnabled屬性時遇到問題。通常它工作正常,但是當我初始化視圖的初始化事件中的IsEnabled狀態時,動態樣式化不再起作用。Wpf:在代碼後面設置IsEnabled中斷樣式觸發器
這是我的代碼。我把它縮小到我能做到的最簡單的例子。
爲什麼會出現這種情況,我該怎麼做才能讓我通過樣式觸發器並在代碼後面初始化IsEnabled?
在此先感謝!
查看:
(包含應取決於複選框的值啓用/禁用的文本框)
<Window x:Class="IsEnabled.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Initialized="Window_Initialized">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtTarget" Width="200">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ToggleValue}" Value="True">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<CheckBox x:Name="chkSource" IsChecked="{Binding Path=ToggleValue}" />
</StackPanel>
</Window>
查看代碼隱藏:
(唯一增加是爲IsEnabled設置初始狀態的初始化事件的執行)
using System;
using System.Windows;
namespace IsEnabled.Views
{
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
}
private void Window_Initialized(object sender, EventArgs e)
{
txtTarget.IsEnabled = false;
}
}
}
視圖模型:
(ViewModelBase持有INotifyPropertyChanged接口的實現)
using System;
namespace IsEnabled.ViewModels
{
class MainViewModel : ViewModelBase
{
private bool _ToggleValue;
public bool ToggleValue
{
get { return _ToggleValue; }
set
{
_ToggleValue = value;
OnPropertyChanged(this, "ToggleValue");
}
}
}
}