簡體   English   中英

如何正確公開自定義控件上的屬性?

[英]How do I correctly Expose a property on a custom control?

我正在嘗試在Xamarin.Forms創建自定義控件並正確公開屬性。 我確信同樣的原則適用於WPF

我的控制

public class ExtendedMap : Map
{
    public ExtendedMap()
    {

    }

    private IList<Pin> _staticPins;
    public IList<Pin> StaticPins
    {
        get { return _staticPins; }
        set { _staticPins = value;}
    }
}

Xaml 中,我目前正在使用它:

<custom:ExtendedMap x:Name="map" Grid.Row="2" HorizontalOptions="Fill" VerticalOptions="Fill" IsVisible="{Binding CustomerSearchControlViewModel.MapIsDisplayed}">
  <custom:ExtendedMap.StaticPins>
    <x:Array Type="{x:Type maps:Pin}">
      <maps:Pin Label="Hello" Address="{Binding CustomerSearchControlViewModel.SelectedCustomer.Address, Converter={StaticResource AddressToStringConverter}" Position="{Binding CustomerSearchControlViewModel.SelectedCustomer.Position}" Type="Place"/>
    </x:Array>
  </custom:ExtendedMap.StaticPins>
</custom:ExtendedMap>

如果我取出<x:Array>部分,我會收到一個錯誤:

序列不是 IEnumerable

但我想像這樣使用它:

<custom:ExtendedMap.StaticPins>
      <maps:Pin Label="Hello" Address="{Binding CustomerSearchControlViewModel.SelectedCustomer.Address, Converter={StaticResource AddressToStringConverter}" Position="{Binding CustomerSearchControlViewModel.SelectedCustomer.Position}" Type="Place"/>
 </custom:ExtendedMap.StaticPins>

這可能嗎? 這樣做的正確方法是什么?

WPF 中最糟糕的問題是什么?

3) 如果 XAML 要將屬性識別為集合屬性,則屬性的類型必須實現IList ,而不是IList<T>

不幸的是,更一般地說,XAML 和泛型類型不能很好地協同工作。

如果這不能解決您的問題,請改進您的問題。 提供一個好的、最小的完整的代碼示例,可靠地重現問題,以便更清楚地了解場景是什么。

您可能還對如何嵌套自定義 XAML 元素感興趣 ,它展示了如何將屬性聲明為 XAML 中子元素的默認集合。

感謝@Peter Duniho 的回答,它迫使我朝着正確的方向前進。 這是他提到的幾點的綜合。

首先我必須在我的ExtendedMap上實現IList以便我可以在Xaml設置項目列表而不使用Array

最終的解決方案如下所示:

public class ExtendedMap : Map : IList
{
    public ExtendedMap()
    {

    }

    private IList<Pin> _staticPins = new List<Pin>();
    public IList<Pin> StaticPins
    {
        get { return _staticPins; }
        set { _staticPins = value;}
    }

    //..IList Implementations

    Public int Add(object item)
    {
       var pin = (Pin)item;
       StaticPins.Add(pin);
       return 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM