设置 ChildWindow 标题的样式
我是 C# 和 wpf 的新手。我有一个 ChildWindow,其标题是从类外部设置的。如果标题太长,我需要缩短标题并在末尾添加省略号。我通过这样做完成了(代码被缩短):
<Namespace:ChildWindow
x:Class="Namespace.MyClass">
<Namespace:ChildWindow.Title>
<TextBlock x:Name="_titleBlock" Width="300" TextTrimming="WordEllipsis"/>
</Namespace:ChildWindow.Title>
</Namespace:Childwindow>
但是,我希望此类的调用者能够设置 ChildWindow.Title = "Something long"
而不是 ChildWindow._titleBlock = “有些长”
因为我认为这更有意义。是否可以通过事件以某种方式做到这一点?
I'm new-ish to C# and wpf. I have a ChildWindow whose title gets set from outside the class. I need the title to be shortened with ellipsis on the end if it is too long. I accomplished by doing this (the code is shortened):
<Namespace:ChildWindow
x:Class="Namespace.MyClass">
<Namespace:ChildWindow.Title>
<TextBlock x:Name="_titleBlock" Width="300" TextTrimming="WordEllipsis"/>
</Namespace:ChildWindow.Title>
</Namespace:Childwindow>
However, I would like caller of this class to be able to set ChildWindow.Title = "Something long"
rather than ChildWindow._titleBlock = "Something long"
because I think that it makes more sense. Is it possible to do this through events somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您真正想做的是使用 MVVM 模式来分割您的从你的观点来看逻辑。这样,您就可以将 ViewModel 传递给操作子窗口的对象,而不是子窗口本身。
例如,子窗口的基本 ViewModel 可以是:
然后,在创建子窗口时将 DataContext 设置为视图模型,如下所示:
并将子窗口标题挂接到 Xaml 中的 ViewModel,如下所示:
然后当您想要时要更改标题,您可以使用
在 ViewModel 上设置标题将触发 PropertyChanged 事件,这将导致 Xaml 视图使用新设置的值更新自身。这可能看起来是一种非常冗长的做事方式,但如果您花几分钟思考一下这可以让您做什么,您会发现一些巨大的好处。绑定远远超出了简单的标题文本...
希望这一切都能按原样工作,但我是凭记忆做的,所以对任何错误感到抱歉...
What you really want to do is use the MVVM pattern to split your logic out from your view. That way you can pass your ViewModel to the thing manipulating the child window instead of the child window itself.
For example, a basic ViewModel for the child window could be:
You then set the DataContext to the viewmodel when you create the child window like this:
and hook the child windows Title up to the ViewModel in the Xaml like this:
Then when you want to change the title you can use
Setting the title on the ViewModel will trigger the PropertyChanged event which will cause the Xaml view to update itself with the newly set value. This might seem like a VERY long winded way of doing things but if you think about what this allows you to do for a few minutes you'll see some huge benefits. The binding goes way beyond simple title texts...
Hopefully that will all work as is but I'm doing it from memory so sorry for any mistakes...