我创建了一个实现ICommandSource的TextBox实例,我想通过DataContext控制IsEnabled属性。我的代码的这部分工作,除此之外,我想通过相同的方法或扩展IsEnabled属性来控制Text属性。
基本上,当TextBox从IsEnabled =“False”转换为IsEnabled =“True”时,我想将Text字段重置为空字符串,或者最好为null。
我试图以一些方式做到这一点但没有成功。
尝试1
<ctrl:CommandTextBox x:Name="txtSerialNumber"
Command="{Binding VMFactory.CreateViewModelCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
CommandParameter="{Binding Text, RelativeSource={RelativeSource Self}}" DecoderPrefix="S">
<ctrl:CommandTextBox.Style>
<Style TargetType="{x:Type ctrl:CommandTextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="True" />
<Setter Property="Text" Value="{x:Null}" />
</DataTrigger>
</Style.Triggers>
<Setter Property="IsEnabled" Value="False" />
<Setter Property="Text" Value="{Binding SerialNumber, Mode=OneWay}" />
</Style>
</ctrl:CommandTextBox.Style>
</ctrl:CommandTextBox>
这确实有效,但只有在CommandParameter不需要“解码”时才有效。似乎当我的text属性通过覆盖更改时,它会中断触发器直到应用程序重新启动。
CommandTextBox.cs
public class CommandTextBox : DecoderTextBox, ICommandSource
{
// Additional Fields, Properties, and Methods removed for the sake of brevity.
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter && Command != null)
{
RoutedCommand command = Command as RoutedCommand;
if (command != null)
command.Execute(CommandParameter, CommandTarget);
else
Command.Execute(CommandParameter);
if (CommandResetsText)
this.Text = String.Empty;
e.Handled = true;
}
}
}
DecoderTextBox.cs
public class DecoderTextBox : TextBox
{
public static DependencyProperty DecoderPrefixProperty = DependencyProperty.Register("DecoderPrefix", typeof(string), typeof(DecoderTextBox), new PropertyMetadata(String.Empty));
public string DecoderPrefix
{
get { return (string)GetValue(DecoderPrefixProperty); }
set { SetValue(DecoderPrefixProperty, value); }
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
string text = this.Text;
// If the if statement returns true the trigger will break.
if (text.Substring(0, Math.Min(DecoderPrefix.Length, text.Length)) == DecoderPrefix)
this.Text = text.Remove(0, DecoderPrefix.Length);
}
base.OnKeyDown(e);
}
}
我的OnKeyDown实现是否有特定的东西打破了这个触发器?
答案 0 :(得分:0)
存在与在本地设置DependencyProperty的值相关的问题。看起来好像你必须使用SetCurrentValue来维护绑定。
<强> DecoderTextBox.cs 强>
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (Text.StartsWith(DecoderPrefix))
SetCurrentValue(TextProperty, Text.Remove(0, DecoderPrefix.Length));
}
base.OnPreviewKeyDown(e);
}