在我已经创建了一个控件,它有一个文本框和一个文本更改事件处理程序附加到它 - 这是在XAML。当控件加载时文本改变了事件,需要防止加载?
问题:当控件加载时,文本更改事件被触发,我不希望它发生在控件加载时,只有当我通过键入内容实际上使其在控件上发生更改时才加载控件。
你的专业人士建议我做什么? :)
在我已经创建了一个控件,它有一个文本框和一个文本更改事件处理程序附加到它 - 这是在XAML。当控件加载时文本改变了事件,需要防止加载?
问题:当控件加载时,文本更改事件被触发,我不希望它发生在控件加载时,只有当我通过键入内容实际上使其在控件上发生更改时才加载控件。
你的专业人士建议我做什么? :)
将您的EventHandler附加在您的构造函数中的InitializeComponent
方法之后而不是Xaml
中。
即
public MainWindow()
{
InitializeComponent();
textBox1.TextChanged+=new TextChangedEventHandler(textBox1_TextChanged);
}
我注意到,你在谈论的用户控件,我能想到的把我的头顶部的唯一要做的就是创建一个可以用来抑制特性直到父窗体完成加载TextChanged事件。看看这样的事情是否有效。
的MainForm的XAML:
<my:UserControl1 setInhibit="True" HorizontalAlignment="Left" Margin="111,103,0,0" x:Name="userControl11" VerticalAlignment="Top" Height="55" Width="149" setText="Hello" />
MainForm的CS
private void Window_Loaded(object sender, RoutedEventArgs e)
{
userControl11.setInhibit = false;
}
用户控件:
public UserControl1()
{
InitializeComponent();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
public string setText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public bool setInhibit { get; set; }
void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (setInhibit) return;
// Do your work here
}
UserControl1.xaml:
<Grid>
<TextBox Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}" TextChanged="TextBox_TextChanged"/>
</Grid>
其中框TextChanged为文本框原始事件
UserControl1.xaml.cs:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
_isFirstTime = true;
DataContext = this;
InitializeComponent();
}
public event TextChangedEventHandler TextBoxTextChanged;
bool _isFirstTime;
//MyText Dependency Property
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""));
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (TextBoxTextChanged != null)
if (!_isFirstTime)
{
TextBoxTextChanged(sender, e);
}
_isFirstTime = false;
}
}
其中TextBox_TextChanged为原始框TextChanged 和TextBoxTextChanged更像原始的包装框TextChanged
定制事件处理程序Window.xaml:
<Grid>
<c:UserControl1 TextBoxTextChanged="TextBoxValueChanged"/>
</Grid>
当你看到你可以添加一个事件处理程序的事件包装(TextBoxTextChanged)
Window.xaml.cs:
private void TextBoxValueChanged(object sender, TextChangedEventArgs e)
{
MessageBox.Show("asd");
}
终于TextBoxValueChanged不会在第一时间文本更改
解雇所有你需要做的是检查处理它之前,事件处理程序中的文本框的IsLoaded属性。
代码示例将有所帮助;) – Sisyphe