如何从Xamarin形式的视图模型中水平列出视图项的选项值

时间:2019-09-25 10:30:06

标签: forms xamarin

我有listview,我需要根据viewmodel的条件设置stacklayout水平选项值。因此如何设置

私有字符串horizo​​ntalOption;

    public string HorizontalOption
    {
        get => horizontalOption;
        set
        {
            horizontalOption = value;
            OnPropertyChanged(nameof(HorizontalOption));
        }
    }

public async Task FetchThreadUserData()
    {
     sing (HttpClient hc = new HttpClient())
        {
            try
            {
                IsBusy = true;
                var jsonString = await hc.GetStringAsync(url);
                var obj = JsonConvert.DeserializeObject<MessageList>(jsonString);
                foreach (var user in obj.messages)
                {
                    string authorIdStr = user.authorId;
                    if(authorIdStr==userId)
                    {
                        HorizontalOption = "StartAndExpand";
                    }
                    else if(authorIdStr!=userId)
                    { 
                    HorizontalOption = "EndAndExpand"; 
                    }
                    list.Add(user);
                }
            }
 and binding it like this in Xaml
<StackLayout HorizontalOptions="{Binding HorizontalOption}" >
but it is not working .

3 个答案:

答案 0 :(得分:0)

如果要让列表水平滚动,可以在Forms中使用 CollectionView CollectionView 在XF 4.0之后发布。

<CollectionView ItemsSource="{Binding xxx}">
    <CollectionView.ItemsLayout>
        <ListItemsLayout Orientation="Horizontal" />
    </CollectionView.ItemsLayout>

     <CollectionView.ItemTemplate>
        <DataTemplate>

          //...
        </DataTemplate>
    </CollectionView.ItemTemplate>

</CollectionView>

在调用Forms.Init之前,请不要忘记在iOS的AppDelegate类或Android的MainActivity类中添加以下代码行:

Forms.SetFlags("CollectionView_Experimental");

答案 1 :(得分:0)

您可以简单地使用DataTriggers来基于某些ViewModel属性值来更改Horizo​​ntalOptions ...

按如下所示更新您的媒体资源...

public bool HorizontalOption
{
    get => horizontalOption;
    set
    {
        horizontalOption = value;
        OnPropertyChanged(nameof(HorizontalOption));
    }
}

现在如下更新您的Xaml代码...

<StackLayout>
//Your UI Elements here
  <StackLayout.Triggers>
     <DataTrigger TargetType="StackLayout" Binding="{Binding HorizontalOption}" 
        Value="True">
        <Setter Property="HorizontalOptions" Value="StartAndExpand"/>
     </DataTrigger>
     <DataTrigger TargetType="StackLayout" Binding="{Binding HorizontalOption}" 
        Value="False">
        <Setter Property="HorizontalOptions" Value="EndAndExpand"/>
     </DataTrigger>
  </StackLayout.Triggers>
</StackLayout>

注意:-在您的方法FetchThreadUserData()中,将Horizo​​ntalOption属性值更新为True或False ...

希望这会有所帮助

答案 2 :(得分:0)

它不起作用,因为您正在将字符串绑定到接受LayoutOptions的属性。

public Xamarin.Forms.LayoutOptions HorizontalOption
{
    get => horizontalOption;
    set
    {
        horizontalOption = value;
        OnPropertyChanged(nameof(HorizontalOption));
    }
}