Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 文本框边框笔刷在文本更改后不更新_C#_Wpf_Binding_Textbox_Converter - Fatal编程技术网

C# 文本框边框笔刷在文本更改后不更新

C# 文本框边框笔刷在文本更改后不更新,c#,wpf,binding,textbox,converter,C#,Wpf,Binding,Textbox,Converter,我有带默认边框笔刷的WPF文本框。当文本框内容为空时,我想将边框笔刷更改为红色。这是我的密码: <TextBox Width="200" Text="{Binding Path=Description}" Name="tbDescription" Grid.Row="1" Grid.Column="2" Margin="2" BorderBrush="{Binding RelativeSource={RelativeSource

我有带默认边框笔刷的WPF文本框。当文本框内容为空时,我想将边框笔刷更改为红色。这是我的密码:

<TextBox Width="200" Text="{Binding Path=Description}" Name="tbDescription" Grid.Row="1" Grid.Column="2" Margin="2" 
                             BorderBrush="{Binding RelativeSource={RelativeSource Self},
                             Path=Text,
                             Converter={StaticResource borderBrushColorConverter}}">

问题是,只有当文本框焦点丢失时,边框才会变成红色。我试着在Background属性上使用相同的代码,而不是在BorderBrush上,然后一切都正常了

你可以试试这个,把
Tempalte

<TextBox BorderBrush="{Binding RelativeSource={RelativeSource Self},
                         Path=Text,
                         Converter={StaticResource borderBrushColorConverter}}">
        <TextBox.Style>
            <Style  TargetType="{x:Type TextBox}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TextBox}">
                            <Border x:Name="Bd" 
                                    SnapsToDevicePixels="true" 
                                    Background="{TemplateBinding Background}" 
                                    BorderBrush="{TemplateBinding BorderBrush }"
                                    BorderThickness="{TemplateBinding BorderThickness}" 
                                    Width="{TemplateBinding Width}" 
                                    Height="{TemplateBinding Height}">
                                <ScrollViewer x:Name="PART_ContentHost"></ScrollViewer>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>

也许您试图解决的问题不仅仅是条件样式,而是数据验证的问题。如果是这样的话,那么值得考虑在视图模型中添加对
IDataErrorInfo
的支持,或者更好的是
INotifyDataErrorInfo

以下是后者在视图模型上的可能实现,基于每次属性更改后执行的
Validate
方法,以及根据属性错误存储执行的
Dictionary

public class MyViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
    public string Description
    {
        get { return _description; }

        set
        {
            _description = value;
            NotifyPropertyChanged();
            Validate();
        }
    }

    private string _description;

    private void Validate()
    {
        Errors[nameof(Description)].Clear();

        if (string.IsNullOrEmpty(Description))
        {
            Errors[nameof(Description)].Add("The text cannot be empty");
        }

        if (Errors[nameof(Description)].Any())
        {
            NotifyErrorsChanged(nameof(Description));
        }
    }

    public IEnumerable GetErrors(string propertyName)
        => Errors.ContainsKey(propertyName) ? Errors[propertyName] : Enumerable.Empty<string>();

    public bool HasErrors
        => Errors.Any(propertyErrors => (propertyErrors.Value ?? Enumerable.Empty<string>()).Any());

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    protected virtual void NotifyErrorsChanged([CallerMemberName] string propertyName = null)
        => ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));

    private IDictionary<string, List<string>> Errors { get; }
        = new Dictionary<string, List<string>>
        {
            {nameof(Description), new List<string>()}
        };

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
公共类MyViewModel:INotifyPropertyChanged,INotifyDataErrorInfo
{
公共字符串描述
{
获取{return\u description;}
设置
{
_描述=值;
NotifyPropertyChanged();
验证();
}
}
私有字符串描述;
私有void Validate()
{
错误[名称(说明)]。清除();
if(string.IsNullOrEmpty(Description))
{
错误[名称(说明)]。添加(“文本不能为空”);
}
if(错误[nameof(Description)].Any())
{
NOTIFYERRSCHANGED(名称(说明));
}
}
公共IEnumerable GetErrors(字符串propertyName)
=>Errors.ContainsKey(propertyName)?Errors[propertyName]:Enumerable.Empty();
公共布尔错误
=>Errors.Any(propertyErrors=>(propertyErrors.Value??Enumerable.Empty()).Any());
公共事件事件处理程序错误更改;
受保护的虚拟void NOTIFYERRSCHANGED([CallerMemberName]字符串propertyName=null)
=>ErrorsChanged?.Invoke(这是新的DataErrorsChangedEventArgs(propertyName));
私有IDictionary错误{get;}
=新词典
{
{nameof(Description),new List()}
};
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void NotifyPropertyChanged([CallerMemberName]字符串propertyName=null)
=>PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName));
}
视图侧减少为以下内容:

<TextBox Text="{Binding Description, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />


问题在于,默认情况下,WPF在文本框聚焦时会在其周围添加一个蓝色边框。您应该尝试寻找一种方法来删除该边界。尝试此链接:()如果您将绑定模式更改为
PropertyChanged
,而不是默认的
LostFocus
,是否有效
Text=“{Binding Path=Description,Mode=PropertyChanged}”
不要在这里使用转换器,使用
DataTrigger创建
Style
<TextBox Text="{Binding Description, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />