[英]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.