[英]C# how to bind a property to display it in an XAML-Element
我想要 output 來自視圖 model(這里是汽車品牌)的視圖元素中的值。 SubView 只包含一個 label 並且應該顯示它。 如果我將 label 更改為文本框和哪個綁定,該值將在 ViewModel 中顯示給我!
XAML:
<Grid>
<Label FontSize="32" Content="{Binding CarModel}" Background="GreenYellow" Height="55" Width="288">
<Label.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"></Setter>
</Style>
</Label.Resources>
</Label>
</Grid>
視圖模型
class CarVM : CarBase
{
private tblCars _carModel;
public ObservableCollection<tblCars> AllCars { get; }
...
public tblCars CarModel
{
get { return _carModel; }
set
{
value;
}
}
...
}
你記得設置綁定上下文嗎? 我也不知道你使用的是哪種項目類型。 如果它是一個 Xamarin Forms 項目,則 label 內容屬性被命名為“文本”,否則如果它是 WPF 則它是“內容”
還要確保您的 Carmodel 不是 null - 設置斷點並在綁定發生時在運行時檢查它。 如果在視圖初始化后加載 model,則需要在設置值后調用 OnPropertyChanged("CarModel")。 有多種方法可以設置 BindingContext - 這是一種方法:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new CarVM();
}
}
class CarVM : BindableObject
{
private tblCars _carModel;
public tblCars CarModel
{
get { return _carModel; }
set
{
if (_carModel != value)
{
_carModel = value;
OnPropertyChanged();
}
}
}
public CarVM()
{
}
}
如果您已經設置了 BindingContext,您可以通過 object 中的“點”來找到您想要顯示的屬性
<Grid>
<Label FontSize="32" Content="{Binding CarModel.SomePropertyYouWantToBindTo}" Background="GreenYellow" Height="55" Width="288">
<Label.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"></Setter>
</Style>
</Label.Resources>
</Label>
</Grid>
你越來越接近了。 我認為您嘗試 go 的問題有點短,您可能需要編輯您的帖子並提供更多詳細信息。 就目前而言,您的 tblCars 是 object 的類型(暗示一張汽車表),但屬性CarModel是實際暴露的東西,它可能有其他組件,如 model、年份、顏色、制造商。
您的視圖 label 正在設置它與事物的綁定,而不是單個字符串/整數/任何值,因此 label 無法真正向您顯示任何內容。
您可能首先需要將 GRID 設置為當前 TblCars 的綁定,然后讓 label 引用您要顯示的汽車的單個元素/屬性。 讓我為你擴展一下
public class SingleCar
{
public string Mfg {get; set;}
public string Color {get; set;}
public string Model {get; set;}
}
public SingleCar OneCarForTheView {get; set;}
然后,在您的綁定中,您將綁定到 OneCarForTheView,您的 label 將是汽車的 Model、顏色或制造商。 您視圖中的綁定可以是部分粒度的點符號,也可以是 object 本身的一個父級,然后只綁定到屬性本身。 如
<Grid DataContext={Binding OneCarForTheView}>
<Label Content="{Binding Model}" />
<Label Content="{Binding Color}" />
<Label Content="{Binding Mfg}" />
</Grid>
或者
<Grid>
<Label Content="{Binding OneCarForTheView.Model}" />
<Label Content="{Binding OneCarForTheView.Color}" />
<Label Content="{Binding OneCarForTheView.Mfg}" />
</Grid>
但是,您的視圖本身確實需要將其“DataContext”設置為您的視圖 model,以便這些屬性是可用於獲取綁定的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.