Jas*_*era 22 wpf dependency-properties wpf-controls
即使是最基本的例子,我也会疯狂地试图让它工作.我不能为我的生活得到约束力.这是一个不适合我的超级简单示例.我必须做错事.
我的控件库程序集中的自定义控件:
public class TestControl : Control
{
public static readonly DependencyProperty TestPropProperty =
DependencyProperty.Register("TestProp", typeof(string), typeof(TestControl), new UIPropertyMetadata(null));
public string TestProp
{
get { return (string)GetValue(TestPropProperty); }
set { SetValue(TestPropProperty, value); }
}
static TestControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl)));
}
}
Run Code Online (Sandbox Code Playgroud)
它的XAML模板:
<Style TargetType="{x:Type local:TestControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TestControl}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel>
<TextBlock Text="Testing..." />
<Label Content="{Binding TestProp}" Padding="10" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
这是XAML在wpf窗口中使用控件来引用我的控件库:
<Grid>
<ItemsControl Name="mylist">
<ItemsControl.ItemTemplate>
<DataTemplate>
<my:TestControl TestProp="{Binding Path=Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)
这是背后的代码:
public partial class Test2 : Window
{
public class TestObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
private int _id;
public int id
{
get { return _id; }
set { _id = value; OnPropertyChanged("id"); }
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; OnPropertyChanged("Name"); }
}
}
public Test2()
{
InitializeComponent();
mylist.ItemsSource = new TestObject[]
{
new TestObject(){ id = 1, Name = "Tedd" },
new TestObject(){ id = 2, Name = "Fred" },
new TestObject(){ id = 3, Name = "Jim" },
new TestObject(){ id = 4, Name = "Jack" },
};
}
}
Run Code Online (Sandbox Code Playgroud)
运行此示例为我提供了四个控件实例,但是我只在每个实例上看到"Testing ..."TextBlock.我的标签永远不受约束.我误解了什么,做错了什么?
Cle*_*ens 22
您尚未设置正确的绑定源.你要么必须设置RelativeSource:
<Label Content="{Binding TestProp, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
Run Code Online (Sandbox Code Playgroud)
或者使用TemplateBinding:
<Label Content="{TemplateBinding TestProp}"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17965 次 |
| 最近记录: |