c# - 从 WPF 中的外部类绑定
问题描述
我在 MainWindow.xaml 中手动绑定了TextBlock
<TextBlock Name="TestPrice"
Height="30"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Text="{Binding Path=
ScreenMarketLogger, Mode=Default, UpdateSourceTrigger=PropertyChanged}"/>
在MainWindow.xaml.cs我用属性定义类:
public class ScreenLoggerBind : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _ScreenMarketLogger;
public string ScreenMarketLogger
{
get
{
return _ScreenMarketLogger;
}
set
{
_ScreenMarketLogger = value;
OnPropertyChanged("ScreenMarketLogger");
}
}
private string _CurrentPrice;
public string CurrentPrice
{
get
{
return _CurrentPrice;
}
set
{
_CurrentPrice = value;
OnPropertyChanged("CurrentPrice");
}
}
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public ScreenLoggerBind()
{
this.ScreenMarketLogger = "\r\n begin \r\n";
}
}
我有另一个类(实际上这是单独的文件),我在其中定义ScreenLoggerBind类的构造函数。
class ExternalClass
{
...
ScreenLoggerBind ScreenLogger = new ScreenLoggerBind();
...
}
现在我将DataContext转移到这个类中,如下所示:
public void Init(MainWindow mw)
{
mw.TestPrice.DataContext = ScreenLogger;
}
并像这样在mainWindow方法中的MainWindow.xaml.cs中调用此函数
ExternalClass ext = new ExternalClass()
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
ext.Init(this);
}
如果我为变量ScreenLogger.ScreenMarketLogger分配一个值,我会在主 WPF 表单上看到结果。在这里一切正常。
现在提问。如果我在MainWindow.xaml.cs中动态创建组件,例如:
Label lbl_Price = new Label();
lbl_Price.Name = string.Format("lbl_Price_{0}{1}", i.ToString(), cell.ToString());
Binding lbl_PriceBinding = new Binding("Content");
lbl_PriceBinding.Source = ScreenLogger.CurrentPrice;
lbl_PriceBinding.Mode = BindingMode.Default;
lbl_PriceBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
lbl_Price.SetBinding(Label.ContentProperty, lbl_PriceBinding);
....
并在外部类ExternalClass.cs中定义 DataContext
public void Init(MainWindow mw)
{
mw.TestPrice.DataContext = ScreenLogger;
foreach (Label lbl in mw.ChainGrid.Children.OfType<System.Windows.Controls.Label>())
{
if (lbl.Name == "lbl_XName_Price_00")
{
lbl.DataContext = ScreenLogger;
}
}
}
这是行不通的!我看到在主窗体上动态创建了标签。但是,如果我为ScreenLogger.CurrentPrice变量赋值,我看不到任何变化。
为什么?我在哪里犯错了?
解决方案
尝试执行以下操作:
Binding lbl_PriceBinding = new Binding("CurrentPrice");
lbl_PriceBinding.Source = ScreenLogger;
lbl_PriceBinding.Mode = BindingMode.OneWay;
您必须在Binding
构造函数中提供源属性的路径。在您的情况下,源是ScreenLogger
,相对于它的路径是CurrentPrice
.
推荐阅读
- excel - Excel VBA .替换不替换文本
- angular - 导航到特定路由而不重新加载页面但更新 router.url
- xml - 如何使用节点从 TSQL 中的 XML 获取数据?
- spring-boot - 在带有 Spring Boot 的 Swagger 安全方案上使用两个 API 密钥
- ios - UITextView Height 如何增加它的某个点
- oauth-2.0 - 如何为修改其他电子表格和幻灯片的脚本启用权限?
- python - 匹配 ORB 特征并使用它们来查找同应性
- python - 无法找到 matplotlib 配置文件 .mplstyle 的正确文档
- python - Herepy EV充电站API;发生错误:禁止访问,说明:这些凭据未授权访问
- r - 在条件下选择R中的多个字符串值