Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在代码隐藏中更改帧的背景色?_C#_Xamarin.forms - Fatal编程技术网

C# 如何在代码隐藏中更改帧的背景色?

C# 如何在代码隐藏中更改帧的背景色?,c#,xamarin.forms,C#,Xamarin.forms,我正在使用xamarin为android、iOS和WP创建一个应用程序。在我的一个页面中,我在DataTemplate中有一个框架,我无法访问代码背后的框架元素,所以我将框架的backgroundcolor绑定到一个变量。当用户点击一个按钮时,颜色应该会改变,但不会改变 XAML: <CollectionView x:Name="collectionView"> <CollectionView.EmptyView> <Label Text="Não

我正在使用xamarin为android、iOS和WP创建一个应用程序。在我的一个页面中,我在DataTemplate中有一个框架,我无法访问代码背后的框架元素,所以我将框架的backgroundcolor绑定到一个变量。当用户点击一个按钮时,颜色应该会改变,但不会改变

XAML:

<CollectionView x:Name="collectionView">
   <CollectionView.EmptyView>
      <Label Text="Não foram encontrados contactos com email" x:Name="SemContactos" IsVisible="False"  AbsoluteLayout.LayoutBounds="0.5,0.5,100,100" AbsoluteLayout.LayoutFlags="PositionProportional"/>
   </CollectionView.EmptyView>
   <CollectionView.ItemsLayout>
      <GridItemsLayout Orientation="Vertical" Span="2"/>
   </CollectionView.ItemsLayout>
   <CollectionView.ItemTemplate>
      <DataTemplate x:Name="template">
         <Grid Padding="5" x:Name="grid">
            <Grid.RowDefinitions>
               <RowDefinition Height="50"/>
               <RowDefinition Height="25"/>
               <RowDefinition Height="25"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
               <ColumnDefinition Width="70"/>
               <ColumnDefinition Width="70"/>
            </Grid.ColumnDefinitions>
            <Frame BackgroundColor="{DynamicResource myResourceKey}"
               OutlineColor="LightGray"
               CornerRadius="3" Padding="0.5" Grid.RowSpan="3" Grid.ColumnSpan="5" x:Name="frameContacto">
            <Frame.GestureRecognizers>
               <TapGestureRecognizer Tapped="ContactoSelecionado" />
            </Frame.GestureRecognizers>
            <StackLayout  Spacing="5">
               <Image  x:Name="imageX" Grid.RowSpan="2" Grid.ColumnSpan="2" 
                  Source="{Binding Foto}"
                  Aspect="AspectFill"
                  HeightRequest="60"
                  WidthRequest="60"
                  HorizontalOptions="Center" />
               <!--Source="{local:ImageResource KiaiDay.Images.user.png}"-->
               <Label Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding Nome}" FontAttributes="Bold" HorizontalOptions="Center" VerticalOptions="EndAndExpand" TextColor="Black"/>
               <Label Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding Email}" HorizontalOptions="Center" VerticalOptions="StartAndExpand"/>
            </StackLayout>
            </Frame>
         </Grid>
      </DataTemplate>
   </CollectionView.ItemTemplate>
</CollectionView>
<StackLayout AbsoluteLayout.LayoutBounds=".5,1,.5,.1" AbsoluteLayout.LayoutFlags="All" x:Name="butoes" IsVisible="False">
   <StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
      <Button Text="Seleccionar todos" WidthRequest="170" TextColor="White" BackgroundColor="#1E90FF" FontAttributes="Bold" CornerRadius="2" HeightRequest="40" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Clicked="SeleccionarTodos" x:Name="selTodos"/>
      <Button Text="Convidar" WidthRequest="170" TextColor="White" BackgroundColor="#1E90FF" FontAttributes="Bold" CornerRadius="2" HeightRequest="40" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
   </StackLayout>
</StackLayout>

从代码中,框架的颜色位于CollectionView.ItemTemplate中。若要更改项中的颜色,应更改模型的数据,而不是直接通过绑定的资源名称或x:name进行更改

在模型中将MyColor属性添加到模型Monkey中:

如果要动态更改,还需要将InotifyProperty更改为模型:

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
然后在Xaml中绑定MyColor:

最后,您可以在CollectionView选择EdItem时进行测试


您可以将颜色绑定到模型,它将由模型数据更改。您的目标是更改所有帧的背景颜色还是仅更改您单击的帧的背景颜色?您的尝试是通过使用DynamicResource,但是所有帧都看同一个DynamicResource,因此,如果动态资源发生更改,所有帧都将以这种方式更改背景。在您的示例中,如果希望更新DynamicSource,可以将corFrame=Color.LightGray更改为this.Resources[myResourceKey]=Color.LightGray。现在只更改corFrame字段的值,而不更改this.Resources条目。
private string mycolor = "Accent";

public string MyColor
{
   get
   {
      return mycolor;
   }
   set
   {
      if (mycolor != value)
      {
          mycolor = value;
          OnPropertyChanged("MyColor");
      }
    }
 }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
<ContentPage.Resources>
    <ResourceDictionary>
        <CollectionViewDemos:StringToColorConverter x:Key="StringToColorConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

Frame BackgroundColor="{Binding MyColor, Converter={StaticResource StringToColorConverter}}"
public class StringToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //throw new NotImplementedException();
        string valueAsString = value.ToString();
        switch (valueAsString)
        {
            case ("Red"):
                {
                    return Color.Red;
                }
            case ("Accent"):
                {
                    return Color.Accent;
                }
            default:
                {
                    return Color.FromHex(value.ToString());
                }
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
<CollectionView ItemsSource="{Binding Monkeys}"
                SelectionMode="Single"
                SelectedItem="{Binding SelectedMonkey, Mode=TwoWay}">
Monkey selectedMonkey;
public Monkey SelectedMonkey
{
    get
    {
        return selectedMonkey;
    }
    set
    {
        if (selectedMonkey != value)
        {
            selectedMonkey.MyTextColor = "Red"; //Here is changing the color
            selectedMonkey = value;
        }
    }
}