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