如何使用RelativeSource Self的绑定设置文本框的默认文本

时间:2012-11-15 21:11:31

标签: wpf xaml binding

在初始页面加载时,我正在设置它以便表单准备好输入新记录。对于一些自定义数据验证器,我将绑定设置为自身。我的问题是如何将默认文本设置为某些内容?

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

1 个答案:

答案 0 :(得分:4)

在Loaded或Initialized事件上添加事件处理程序,并在那里设置Text。

<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>