Board.xaml
<ListView ItemsSource="{Binding SwitchesList}" HasUnevenRows="True" SeparatorColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="5" BackgroundColor="Transparent">
<Image Source="{Binding ImageURL}"></Image>
<StackLayout HorizontalOptions="StartAndExpand" VerticalOptions="Center">
<Label Text="{Binding Name}" FontSize="22" TextColor="White" VerticalOptions="Center"></Label>
</StackLayout>
<Switch x:Name="{Binding Name}" IsToggled="{Binding State, Mode=TwoWay}" Toggled="Switch_Toggled"></Switch>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Board.xaml.cs
public Board ()
{
InitializeComponent ();
var switchModel = new SwitchModel();
BindingContext = switchModel;
}
将SwitchModel作为ViewModel
public class SwitchModel : INotifyPropertyChanged
{
public List<SwitchDTO> SwitchesList { get; set; }
public SwitchModel()
{
SwitchesList =new List<SwitchDTO>
{
new SwitchDTO { Name = "FanSwitch", ImageURL = "windmill.png" ,State=true},
new SwitchDTO { Name = "LightSwitch", ImageURL = "plug.png" ,State=false},
new SwitchDTO { Name = "Switch3", ImageURL = "light.png" ,State=true}
};
}
string _Name;
public string Name
{
get
{
return _Name;
} set
{
_Name = value;
}
}
//bool _isOwned;
//public event PropertyChangedEventHandler PropertyChanged;
//public bool IsOwned
//{
// get
// {
// return _isOwned;
// }
// set
// {
// _isOwned = value;
// var c = Name;
// // Do any other stuff you want here
// }
//}
}
我已经通过视图模型在列表视图中动态创建了开关,问题是如何在视图模型中触发开关事件以及如何知道使用值“开”或“关”切换哪个开关。
如果我每次使用“查看模型列表”绑定行时都单击“切换事件”后面的代码
我怎么能知道风扇或电灯开关在我的视图模型中已切换,我查看了许多示例,例如https://forums.xamarin.com/discussion/126130/how-to-get-the-id-of-the-toggled-switch-item-in-the-listview,但似乎没有一个示例提供足够的信息,而无需在后面的代码中编写代码。例子
答案 0 :(得分:0)
您可以通过将以下代码添加到Board.xaml.cs
void Switch_Toggled(object sender, EventArgs args)
{
Switch sw1 = sender as Switch;
ViewCell vc1 = sw1.Parent.Parent as ViewCell;
SwitchDTO model = vc1.BindingContext as SwitchDTO;
Console.WriteLine(model.Name);
Console.WriteLine(model.State);
Console.WriteLine(model.ImageURL);
}
如果您真的不想在后面使用代码,则可以将某些属性绑定到switch的IsToggled属性的相同值:
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="5" BackgroundColor="Transparent">
<Image Source="{Binding ImageURL}"></Image>
<StackLayout HorizontalOptions="StartAndExpand" VerticalOptions="Center">
<Label Text="{Binding Name}" FontSize="22" TextColor="Blue" VerticalOptions="Center"
IsVisible="{Binding State}"></Label>
</StackLayout>
<Switch x:Name="switch1" IsToggled="{Binding State}" Toggled="Switch_Toggled" ></Switch>
</StackLayout>
</ViewCell>