WPF - 如何在单击时将文本块中的文本加载到多个控件中
我有这个要求: 例如,文本块的名称显示为“姓氏,名字”,单击后将加载两个文本框控件,其中名字的值加载到其自己的框中,姓氏的值加载到其自己的框中,并准备好进行编辑。虽然我可以轻松地在代码隐藏中编写一堆 if 条件来实现此目的,但我正在寻找更好的方法来避免这种解决方案,因为它没有 WPFism 或 MVVM 处理。另外,我的屏幕上还有很多其他控件需要这种行为,如果我采用仅通过切换可见性来解决它的初始方法,代码很快就会变得丑陋。 WPF中有没有更好的方法来解决这个问题?我是否能够将这些控件分组为自定义控件并定义我的控件模板(但这意味着我需要为屏幕中的所有控件滚动这些内容。)
在这个方向上的任何帮助都会很棒。
谢谢 巴拉
I've this requirement where:
For example, a textblock has a name displayed as "Lastname, Firstname" which upon click will load two textbox controls with Firstname's value loaded into its own box and lastname's value into its own box and keep them ready for editing. While I can easily write a bunch of if conditions in my code-behind to achieve this, I'm looking for better ways of avoiding such a solution as there is no WPFism or MVVM treatment to it. Also, there are a bunch of other controls in my screen that will need this sort of a behavior and the code can soon get ugly if i resort to the initial way of solving it by just toggling visibility.
Is there a better way to solve this in WPF? Would I be able to group these controls into a custom control and define my control template (but that would mean I'll need to roll such things for all the controls in my screen.)
Any help in that direction would be great.
Thanks
Bala
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想进入
DataTemplates
的美妙世界,首先我们将为您的数据创建一个容器类
,然后在托管元素(可能是窗口)的代码后面。您可以声明对象的
ObservableCollection
。(不要忘记在某个地方初始化它,以避免各种不必要的异常)
然后您可以将集合绑定到项目集合,我喜欢
ItemsControl
但这不会给出我们想要的结果。因此,虽然我们可以重写类的
ToString()
来输出一些格式化数据,但我们可以通过重写项目控件的项目模板来做得更好。请注意,我使用带有字符串格式化程序的多重绑定,以便在按钮上正确设置文本格式。
现在,在按钮
Click
事件处理程序上,您可以处理一个项目。由于事件的Sender
将是按钮,而按钮的DataContext
将是它代表的 person 对象,您可以做您想做的事情。您可能还会发现
ListBox
及其SelectedItem
属性在您的特定情况下非常有用。希望这足以让您开始,-Val
Sounds like you want to get into the wonderful world of
DataTemplates
first we'll create a container class for your data
Then, in the code behind of your hosting element (probably window). You can declare and
ObservableCollection<>
of the objects.(dont forget to initialize that somewhere to avoid all kinds of unnecessary exceptions)
Then you can bind the collection to an items collection, i like the
ItemsControl
Except this doesn't give the result we want. So while we could override the
ToString()
of our class to spit out some formatted data, we can do one better by overriding the item template of the items control.Note that I'm using a multi-binding with a string formatter in order to format the text correctly on the buttons.
Now on the Buttons
Click
Event handler, you can process an item. As theSender
of the event will be the button, and theDataContext
of the button will be the person object it represents and you can do what you wish.You might also find the
ListBox
and itsSelectedItem
Property very useful in your particular case.Hopefully this is enough to get you started, -Val