当propertychanged被更新时更新另一个UI元素Xaml
我想知道当propertychanged被调用时是否有可能更新另一个UI元素。当propertychanged被更新时更新另一个UI元素Xaml
下面是一个例子:
public string TestString
{
get { return testString; }
set
{
testString = value;
OnPropertyChanged("TestString");
}
}
public TestClass TestClassInstance { get; set; }
假设我的测试类有一个叫做更新方法。如何设置它以便在Xaml中的TestString属性发生更改时调用Update?我知道我总是可以将该方法附加到事件处理程序上,但我想知道是否可以在Xaml中执行此操作。也许使用行为或类似的东西。 你能告诉我这是否可能,如果有的话,你能帮助我走向正确的方向吗?
这听起来像你正在寻找Behaviours
<!-- This collection element might exist if you have already added other behaviors. -->
<i:Interaction.Triggers>
<i:EventTrigger SourceName="textBox" EventName="TextChanged">
<ic:CallMethodAction MethodName="Update" TargetObject="{Binding TestClassInstance}">
</ic:CallMethodAction>
</i:EventTrigger>
</i:Interaction.Triggers>
<Textbox x:Name="textBox" Content="{Binding TestString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
但我不知道你是否能赶上通过此方法从代码更改。如果你的更新方法是一个命令,你应该使用InvokeActionCommand
。
<cmd:InvokeCommandAction Command="{Binding TestClassInstance.Update}"/>
但是,您为什么要把它放入XAML?它是一种非常特定于某个视图或应用程序类型的行为吗?
感谢您的回答! :)。它适用于大多数情况,但是如何让它为用户控制工作?假设我有一个包含列表框的用户控件,并且我想根据用户控件中正在更改的选择来调用一个命令?我如何在主视图中获取这些信息? 例如: ... – CodingMadeEasy 2015-02-09 15:44:09
Nvm。我只是将一个SelectionChanged EventHandler添加到我的用户控件中,并在我的列表框选择已更改时调用它。 – CodingMadeEasy 2015-02-09 16:06:16
您可以使用元素绑定。参考textbox的例子textbloack。 –
2015-02-06 17:30:37
@Ganesh是的我知道你可以将另一个UI元素的元素链接到另一个元素。我的意思是我想在TextBox更改时调用TestClassInstance中的更新方法。我怎么做? – CodingMadeEasy 2015-02-06 18:42:41
只需在代码中更新即可。这不是魔术,在TestString改变时,xaml中的任何内容都不应该“知道”TestClassInstance应该调用Update方法。 – Will 2015-02-06 19:13:29