我正在使用Ca,Xamarin编写的iOS应用程序。我在MVVM体系结构中使用了选择器,并希望更改选择器标题。但是当我使用OnAddMaterial更改Pickers标题时,标题不会更改。
The ViewModel:
private void OnAddNewMaterial()
{
SelectedMaterialIndex = -1;
MaterialPickerTitle = "New Material";
}
private string _materialPickerTitle { get; set; }
public string MaterialPickerTitle
{
get { return _materialPickerTitle; }
set
{
_materialPickerTitle = value;
OnPropertyChanged();
}
}
视图:
<Picker Title="{Binding MaterialPickerTitle}" Margin="12,4,4,4" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" ItemsSource="{Binding Materials}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedMaterial}" SelectedIndex="{Binding SelectedMaterialIndex}" />
我使用Visual Studio 2019。
编辑:当我初始化视图时,我从Picker中设置标题。效果很好。之后,我从Picker将对象分配给ItemSource。当我尝试设置选择器标题之后,它不起作用。
我编写了一个演示,在更改selectedItem之后可以更改Picker的标题。这是您可以参考的代码:
public partial class MainPage : ContentPage
{
List<string> monkeyList = new List<string>();
TestModel model = new TestModel();
public MainPage()
{
InitializeComponent();
monkeyList.Add("Baboon");
monkeyList.Add("Capuchin Monkey");
monkeyList.Add("Blue Monkey");
monkeyList.Add("Squirrel Monkey");
monkeyList.Add("Golden Lion Tamarin");
monkeyList.Add("Howler Monkey");
monkeyList.Add("Japanese Macaque");
picker.ItemsSource = monkeyList;
model.MaterialPickerTitle = "123";
model.SelectedMaterialIndex = 2;
BindingContext = model;
}
private void Button_Clicked(object sender, EventArgs e)
{
monkeyList.Add("Baboonww");
model.SelectedMaterialIndex = -1;
model.MaterialPickerTitle = "456";
}
}
class TestModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public TestModel()
{
}
string materialPickerTitle;
public string MaterialPickerTitle
{
set
{
if (materialPickerTitle != value)
{
materialPickerTitle = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MaterialPickerTitle"));
}
}
}
get
{
return materialPickerTitle;
}
}
int selectedMaterialIndex;
public int SelectedMaterialIndex
{
set
{
if (selectedMaterialIndex != value)
{
selectedMaterialIndex = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SelectedMaterialIndex"));
}
}
}
get
{
return selectedMaterialIndex;
}
}
}
在xaml中:
<StackLayout>
<!-- Place new controls here -->
<Button Clicked="Button_Clicked" Text="click to change title"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Picker x:Name="picker"
Title="{Binding MaterialPickerTitle}"
SelectedIndex="{Binding SelectedMaterialIndex}"
TitleColor="Red">
</Picker>
</StackLayout>
请检查您在项目中的绑定。如果标题更改,请添加一些断点以进行调试。我还上传了示例项目here。