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");
}
}
}
}