将自定义 class 的依赖项 属性 绑定到 UI
bind dependency property from custom class to UI
已经尝试了将近一周的时间来寻找如何将自定义 class(元素)中的我的依赖项 属性 绑定到一个简单的文本框,
每次发送特定数据时,文本框中的文本都必须更改,这只是第一次发生,之后,文本框要更新??
我已经尝试了每一个例子,但我无法达到我的目标,这是我的代码:
对于创建依赖对象的 class :
public class Elements : DependencyObject
{
public static DependencyProperty TextDataProperty = DependencyProperty.Register
(
"TextData",
typeof(string),
typeof(Elements),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender)
);
public string TextData
{
get
{
return (string)GetValue(TextDataProperty);
}
set
{
SetValue(TextDataProperty, value);
}
}
public void UpdateText(string sdata)
{
TextData = sdata;
}
}
我在 xaml 中提到了这个 class 就像这样
xmlns:local="clr-namespace:WpfApplication1"
并使用它:
<Window.Resources>
<local:Elements x:Key="myElements" ></local:Elements>
</Window.Resources>
需要更新的文本框像这样绑定到自定义 class :
<TextBox
Height="23"
HorizontalAlignment="Left"
Margin="12,61,0,0"
Name="textBox1"
VerticalAlignment="Top"
Width="237"
Text="{Binding TextData, Source={StaticResource myElements}}"
/>
我做错了什么??有人可以帮忙吗
根据您的评论:您正在
中创建一个新的 Elements
对象
Elements _elements = new Elements();
_elements.UpdateText(textBox2.Text);
这不是
中用于绑定的对象
Text="{Binding TextData, Source={StaticResource myElements}}"
更改您的代码,使其从资源中访问对象:
var elements = (Elements)Resources["myElements"];
elements.UpdateText(textBox2.Text);
那么您应该将 TextBox 替换为 TextBlock,因为您只想显示文本,但不希望用户对其进行编辑。
您还应该看看 MVVM 设计模式及其在 WPF 中的使用方式。有大量可用的在线资源。
已经尝试了将近一周的时间来寻找如何将自定义 class(元素)中的我的依赖项 属性 绑定到一个简单的文本框, 每次发送特定数据时,文本框中的文本都必须更改,这只是第一次发生,之后,文本框要更新?? 我已经尝试了每一个例子,但我无法达到我的目标,这是我的代码: 对于创建依赖对象的 class :
public class Elements : DependencyObject
{
public static DependencyProperty TextDataProperty = DependencyProperty.Register
(
"TextData",
typeof(string),
typeof(Elements),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender)
);
public string TextData
{
get
{
return (string)GetValue(TextDataProperty);
}
set
{
SetValue(TextDataProperty, value);
}
}
public void UpdateText(string sdata)
{
TextData = sdata;
}
}
我在 xaml 中提到了这个 class 就像这样
xmlns:local="clr-namespace:WpfApplication1"
并使用它:
<Window.Resources>
<local:Elements x:Key="myElements" ></local:Elements>
</Window.Resources>
需要更新的文本框像这样绑定到自定义 class :
<TextBox
Height="23"
HorizontalAlignment="Left"
Margin="12,61,0,0"
Name="textBox1"
VerticalAlignment="Top"
Width="237"
Text="{Binding TextData, Source={StaticResource myElements}}"
/>
我做错了什么??有人可以帮忙吗
根据您的评论:您正在
中创建一个新的Elements
对象
Elements _elements = new Elements();
_elements.UpdateText(textBox2.Text);
这不是
中用于绑定的对象Text="{Binding TextData, Source={StaticResource myElements}}"
更改您的代码,使其从资源中访问对象:
var elements = (Elements)Resources["myElements"];
elements.UpdateText(textBox2.Text);
那么您应该将 TextBox 替换为 TextBlock,因为您只想显示文本,但不希望用户对其进行编辑。
您还应该看看 MVVM 设计模式及其在 WPF 中的使用方式。有大量可用的在线资源。