Accessing DisplayMetrics At Design Time

Nathan Sokalski 4,106 Reputation points
2021-07-20T03:20:51.933+00:00

I have a custom control in my Xamarin.Android app that includes the following property:

public bool WrapTakenString
{
    get { return this._wraptakenstring; }
    set
    {
        this._wraptakenstring = value;
        this.txtTaken.LayoutParameters.Width = this.WrapTakenString ? (int)TypedValue.ApplyDimension(ComplexUnitType.Sp, 125, Application.Context.Resources.DisplayMetrics) : LayoutParams.WrapContent;
    }
}

This works fine during runtime, but if I set it to true during design time, I receive an error in the designer. This leads me to believe that Application.Context.Resources.DisplayMetrics cannot be accessed during design time. However, I am not sure what to replace it with that can be accessed during design time. What should I do?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,348 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,961 Reputation points
    2021-07-21T06:35:00.96+00:00

    Hello @Nathan Sokalski ,​

    Welcome to our Microsoft Q&A platform!

    but if I set it to true during design time, I receive an error in the designer. T

    I created a basic to test the code, it works as expected. After changing the layoutParameter, we need to reset it for the view. Check the code:

       private bool isWorked;  
       public bool IsWorked  
       {  
           get { return isWorked; }  
           set  
           {  
               this.isWorked = value;  
               var layoutParameter = text.LayoutParameters;  
               layoutParameter.Width = IsWorked ? (int)TypedValue.ApplyDimension(ComplexUnitType.Sp, 125, Application.Context.Resources.DisplayMetrics) : LayoutParams.WrapContent;  
               text.LayoutParameters = layoutParameter;  
           }  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.