WPF / WP7의 ListBox에 문자열 목록을 데이터 바인딩하려면 어떻게해야합니까?
문자열 값 목록을 목록 상자에 바인딩하여 값이 한 줄씩 나열되도록 노력하고 있습니다. 지금은 이것을 사용합니다.
<ListBox Margin="20" ItemsSource="{Binding Path=PersonNames}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Id}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
그러나 나는 Id
사용자 정의 클래스가 아닌 모든 문자열 값이기 때문에 대신 텍스트 블록에 무엇을 넣어야할지 모르겠습니다 .
또한 MainPage.PersonNames와 같이 MainPage 내에 있으면 PersonNames를 찾을 필요가 없다고 불평합니다.
데이터 컨텍스트를 다음과 같이 설정했습니다.
DataContext="{Binding RelativeSource={RelativeSource Self}}"
내가 잘못하고 있니?
간단히 ItemsSource가 다음과 같이 바인딩되어 있다고 넣으면 :
YourListBox.ItemsSource = new List<String> { "One", "Two", "Three" };
XAML은 다음과 같아야합니다.
<ListBox Margin="20" Name="YourListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
최신 정보:
이것은 DataContext를 사용할 때의 솔루션입니다. 다음 코드는 페이지의 DataContext와 DataContext의 설정에 전달할 뷰 모델입니다.
public class MyViewModel
{
public List<String> Items
{
get { return new List<String> { "One", "Two", "Three" }; }
}
}
//This can be done in the Loaded event of the page:
DataContext = new MyViewModel();
이제 XAML은 다음과 같습니다.
<ListBox Margin="20" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
이 접근 방식의 장점은 MyViewModel 클래스에 훨씬 더 많은 속성이나 복잡한 개체를 배치하고 XAML에서 추출 할 수 있다는 것입니다. 예를 들어 List of Person 객체를 전달하려면 :
public class ViewModel
{
public List<Person> Items
{
get
{
return new List<Person>
{
new Person { Name = "P1", Age = 1 },
new Person { Name = "P2", Age = 2 }
};
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
그리고 XAML :
<ListBox Margin="20" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
도움이 되었기를 바랍니다! :)
PersonNames에 대한 코드를 보여 주셔야합니다. 확실하지 않습니다. 질문을 이해합니다.하지만 다음과 같이 바인딩하고 싶을 수도 있습니다.
<TextBlock Text="{Binding Path=.}"/>
또는
<TextBlock Text="{Binding"} />
이것은 목록의 현재 요소에 바인딩됩니다. (PersonNames가 문자열 목록이라고 가정). 그렇지 않으면 목록에 클래스 이름이 표시됩니다.
항목 소스가 문자열 항목으로 열거 가능한 경우 다음을 사용하십시오.
<TextBlock Text="{Binding}"></TextBlock>
이 구문은 모든 개체에 사용할 수 있습니다. 일반적으로 ToString () 메소드는 값을 얻기 위해 호출됩니다. 이것은 많은 경우에 매우 편리합니다. 그러나 변경 알림이 발생하지 않습니다.
You can do this without having to explicitly define the TextBlock control as a part of your ListBox (unless you want better formatting). The trick to getting the binding to trigger is using an ObservableCollection<string>
instead of List<string>
Window1.xaml
<ListView Width="250" Height="50" ItemsSource="{Binding MyListViewBinding}"/>
Window1.xaml.cs
public Window1()
{
InitializeComponent();
DataContext = this;
// Need to initialize this, otherwise you get a null exception
MyListViewBinding = new ObservableCollection<string>();
}
public ObservableCollection<string> MyListViewBinding { get; set; }
// Add an item to the list
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
// Custom control for entering a single string
SingleEntryDialog _Dlg = new SingleEntryDialog();
// OutputBox is a string property of the custom control
if ((bool)_Dlg.ShowDialog())
MyListViewBinding.Add(_Dlg.OutputBox.Trim());
}
'Development Tip' 카테고리의 다른 글
중첩 된 사전의 항목에서 Pandas DataFrame 생성 (0) | 2020.11.30 |
---|---|
JsonObject를 문자열로 변환 (0) | 2020.11.30 |
완료 버튼으로 UIPickerView를 만드는 방법은 무엇입니까? (0) | 2020.11.29 |
무료 설치 마법사 소프트웨어 (0) | 2020.11.29 |
Hibernate Criteria를 사용하는 경우 대소 문자를 구분하지 않음 (0) | 2020.11.29 |