wpf 如何设置具有 RelativeSource Self 绑定的文本框的默认文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13406286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set the default text of a textbox with a Binding of RelativeSource Self
提问by TheButlerDidIt
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>
回答by Sisyphe
Add an event handler on the Loaded or Initialized event, and set the Text there.
在 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>
And in the code behind :
在后面的代码中:
private void TextBox_Loaded_1(object sender, RoutedEventArgs e)
{
((TextBox)sender).Text = "Default text";
}
EDIT:
编辑:
XAML only solution :
仅 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>

