는에 TextBlock
상주 DataTemplate
하므로 이름으로 참조 할 수 없습니다. 그렇다면 Text
프로그래밍 방식으로 (예) 속성을 어떻게 바인딩 합니까?
XAML :
<UserControl x:Class="MyNameSpace.MyCustomControl" ... >
...
<ListBox ItemsSource="{Binding Path=ItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
...
</UserControl>
암호:
public partial class MyCustomControl : UserControl {
...
public static readonly DependencyProperty DataSourceProperty =
DependencyProperty.Register("DataSource", typeof (IEnumerable),
typeof (MyCustomControl),
new PropertyMetadata(default(IEnumerable)));
public IEnumerable DataSource {
get { return (IEnumerable) GetValue(DataSourceProperty); }
set { SetValue(DataSourceProperty, value); }
}
public static readonly DependencyProperty MemberPathProperty =
DependencyProperty.Register("MemberPath", typeof (string),
typeof (MyCustomControl),
new PropertyMetadata(default(string)));
public string MemberPath {
get { return (string) GetValue(MemberPathProperty); }
set { SetValue(MemberPathProperty, value); }
}
...
public MyCustomControl() {
InitializeComponent();
var binding = new Binding(MemberPath);
BindingOperations.SetBinding(/*how do I refer to the TextBlock here ???*/,
TextBox.TextProperty, binding);
}
...
}
사용 예 :
<my:MyCustomControl DataSource="{Binding Path=SomeModelCollection}" MemberPath="Name"
어디 SomeModelCollection
와 같은 일부 데이터 모델의 속성이됩니다 ObservableCollection<SomeModel>
( SomeModel
속성은 요구했다 Name
)
당신은 얻을 수 있습니다 TextBlock
사용 VisualTreeHelper
. 이 메서드는 listBoxItem의 시각적 트리에있는 모든 TextBlock을 가져옵니다.
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
where T : DependencyObject
{
if( depObj != null )
{
for( int i = 0; i < VisualTreeHelper.GetChildrenCount( depObj ); i++ )
{
DependencyObject child = VisualTreeHelper.GetChild( depObj, i );
if( child != null && child is T )
{
yield return (T)child;
}
foreach( T childOfChild in FindVisualChildren<T>( child ) )
{
yield return childOfChild;
}
}
}
}
사용법 :
TextBlock textBlock = FindVisualChildren<TextBlock>(listBoxItem)
.FirstOrDefault();
그러나 여전히 코드 뒤에서 수행하는 대신 XAML에서 바인딩을 수행하는 것이 좋습니다.
경우 ItemSource
입니다 ObservableCollection<MyModel>
및 MyModel
속성을 포함 Name
, 그것은 다음과 같이 XAML에서 할 수 있습니다 :
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
이후 DataContext
의 ListBoxItem
것 MyModel
위에서 언급 한 것처럼, 따라서 당신은 이름 속성에 직접 바인딩 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다