How do I set the default text of a textbox with a Binding of RelativeSource Self

萝らか妹 提交于 2019-12-24 11:24:33

问题


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>

回答1:


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>

And in the code behind :

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

EDIT:

XAML only solution :

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


来源:https://stackoverflow.com/questions/13406286/how-do-i-set-the-default-text-of-a-textbox-with-a-binding-of-relativesource-self

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!