[英]How to bind string property to TextBox within ListBox
我使用MVVM將List<string>
綁定到WPF中的ListBox
此刻我有
<ListBox ItemsSource="{Binding FileContents}"></ListBox>
我的ViewModel中的文件內容很簡單
public List<string> FileContents {get;set;}
並且FileContents值是在ViewModel的構造函數中設置的,因此無需擔心INotifyProperty
到目前為止一切正常。 我可以看到在我的顯示列表ListBox
的期望。
現在,我需要提供一個模板! 這就是問題所在
<ListBox ItemsSource="{Binding FileContents}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
這就是所有錯誤的地方! 我的理解是,我只需要執行<TextBox Text = "{Binding}"
因為ListBox已綁定到List<string>
屬性(稱為FileContents)
但是,當我運行上述Visual Studio時,
該應用程序處於中斷模式
如果我將代碼更新為
<TextBox Text = "Some String Value"
然后就可以了
我不明白我做錯了什么。
將Binding
Mode
設置為OneWay
:
<TextBox Text="{Binding Path=., Mode=OneWay}" />
TextBox
的Text
屬性的默認綁定模式是TwoWay
但是當您綁定到List<string>
的string
時,此模式將不起作用。
直接綁定到string
僅是一種方法。 這意味着您只能像
<TextBox Text="{Binding Mode=OneWay}"/>
要么
<TextBox Text="{Binding .}"/>
原因很簡單:更改字符串意味着您要刪除項目並將其添加到列表中。 通過更改TextBox中的字符串,這根本不可能。
一種解決方案是將內容包裝在類似
public class FileContent
{
public string Content { get; set; }
}
並使用<TextBox Text="{Binding Content}"/>
作為模板綁定到List<FileContent>
的List<FileContent>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.