【发布时间】:2015-04-16 15:43:02
【问题描述】:
我正在创建一个运行时文档设计器,为此我需要在画布上显示所选控件的某些属性。所以如果我右键单击一个标签,我需要显示字体系列,字体大小。
我想通过绑定来做到这一点,我确信这是它的完成方式,但似乎无法让代码工作(它没有提供错误,但它也不起作用。引导我认为我的绑定有问题。)请看一下...
TextBlock _source = (TextBlock)sender;
_source.Name = "txtSource";
ContextMenu contxt = new ContextMenu();
contxt.IsOpen = true;
//Font Size Menu Header
MenuItem menuSizeLabel = new MenuItem();
menuSizeLabel.Header = "Font Size";
menuSizeLabel.IsEnabled = false;
contxt.Items.Add(menuSizeLabel);
//Font Size Menu Item
MenuItem menuSize = new MenuItem();
TextBox tbxSize = new TextBox();
Binding FontSizeBinding = new Binding("FontSize");
FontSizeBinding.Source = _source;
FontSizeBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
FontSizeBinding.Mode = BindingMode.TwoWay;
tbxSize.SetBinding(TextBox.FontSizeProperty, FontSizeBinding);
menuSize.Header = tbxSize;
contxt.Items.Add(menuSize);
//Font Size Menu Header
MenuItem menuFontLabel = new MenuItem();
menuFontLabel.Header = "Font Family";
menuFontLabel.IsEnabled = false;
contxt.Items.Add(menuFontLabel);
//Font Menu Item
MenuItem menuFont = new MenuItem();
ComboBox cbxFont = new ComboBox();
foreach (FontFamily font in Fonts.SystemFontFamilies.OrderBy(i => i.ToString()))
{
Label lbl = new Label();
lbl.Content = font;
lbl.FontFamily = font;
cbxFont.Items.Add(lbl);
}
Binding FontBinding = new Binding("FontFamily");
FontBinding.Source = _source;
FontBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
FontBinding.Mode = BindingMode.TwoWay;
tbxSize.SetBinding(ComboBox.FontFamilyProperty, FontBinding);
menuFont.Header = cbxFont;
contxt.Items.Add(menuFont);
}
一切正常,除了当我右键单击时,我想查看大小文本框以显示当前字体值(它显示为空白)。然后当我更新它的值时,我们需要更改所选控件(文本块)的字体大小。
与字体相同。我做错了什么??
【问题讨论】:
-
如此winforms,如此糟糕,非常沮丧..
-
我投了反对票,因为您没有利用 WPF,也没有以预期的方式使用它。我建议学习WPF和WinForms的区别,学习XAML,学习MVVM。这样做会让你的生活轻松很多。
-
不要让我们其他人在尝试阅读并查看问题时流血!
-
你正在学习,但你被否决了......所以太好了。我建议您将信息绑定到 Xaml 中的
ViewModel而不是隐藏代码。 -
我正在学习,mvvm 真的很复杂,一旦我掌握了 wpf,mvvm 应该很简单,但现在我有一个简单的问题。有时我觉得我什至不应该问关于堆栈溢出的问题,因为正义的程序员更喜欢批评编码风格,而不是帮助解决我遇到的一些基本问题。