如何设置带有RelativeSource Self绑定的文本框的默认文本 [英] How do I set the default text of a textbox with a Binding of RelativeSource Self

查看:118
本文介绍了如何设置带有RelativeSource Self绑定的文本框的默认文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在初始页面加载中,我对其进行了设置,以便表单可以输入新记录.对于某些自定义数据验证器,我将绑定设置为其自身.我的问题是如何将默认文本设置为某些内容?

On the initial page load, I am setting it up so that the form is ready to enter a new record. For some custom data validators, I set the binding to itself. My question is how can I set the default text to something?

<TextBox>
    <TextBox.Text>
        <Binding RelativeSource="{RelativeSource Self}"
                 Path="Text"
                 UpdateSourceTrigger="LostFocus" >
            <Binding.ValidationRules>
                <validators:MyCustomValidators />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

推荐答案

在Loaded或Initialized事件上添加事件处理程序,并在此处设置Text.

Add an event handler on the Loaded or Initialized event, and set the Text there.

<TextBox Loaded="TextBox_Loaded_1">
    <TextBox.Text>
        <Binding RelativeSource="{RelativeSource Self}"
                 Path="Text"
                 UpdateSourceTrigger="LostFocus" >
            <Binding.ValidationRules>
                <validators:MyCustomValidators />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

在后面的代码中:

private void TextBox_Loaded_1(object sender, RoutedEventArgs e)
{
    ((TextBox)sender).Text = "Default text";
}

仅XAML解决方案:

<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Setter Property="Text" Value="Default text" />
        </Style>
    </TextBox.Style>
    <TextBox.Text>
        <Binding RelativeSource="{RelativeSource Self}"
                 Path="Text"
                 UpdateSourceTrigger="LostFocus" >
            <Binding.ValidationRules>
                <validators:MyCustomValidators />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

这篇关于如何设置带有RelativeSource Self绑定的文本框的默认文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆